Javaで文字列の一部を削除する


81

1つの文字から文字列の一部を削除したい、つまり:

ソース文字列:

manchester united (with nice players)

ターゲット文字列:

manchester united

5
どの部分を保持し、どの部分を破棄するかをどうやって知るのですか?それを知らずにあなたの質問に答えることは不可能ですか?
レドワルド2013

回答:


156

それを行うには複数の方法があります。置き換える文字列がある場合は、クラスのreplaceまたはreplaceAllメソッドを使用できますString。部分文字列の置き換えを検討している場合は、substringAPIを使用して部分文字列を取得できます。

例えば

String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));

「()」内のコンテンツを置き換えるには、次を使用できます。

int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));

いくつかのタイプミス。あるべきString toBeReplaced = str.substring(startIndex , endIndex + 1);
Yeung

また、スペースを削除する価値があります:System.out.println(str.replace( "(with nice player)"、 ""));
kiedysktos 2016

32

文字列置換

String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");

編集:

インデックス別

s = s.substring(0, s.indexOf("(") - 1);

3
忘れないでくださいs = s.replace(...)
Sergey Kalinichenko 2012年

括弧内は変更される可能性があるため、変更することはできません。文字列を文字から変更する必要があります(
zmki 2012年

19

String.Replace()を使用します。

http://www.daniweb.com/software-development/java/threads/73139

例:

String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");

私は反対票を投じたわけではありませんが、おそらくあなたがReplaceを間違ったケースに入れたからですか?
マイククワン

1
ドライブバイ(つまり、説明がつかず、明らかに疑わしい)の反対票の影響を否定することに賛成票を投じました。
Gayot Fow 2012

文字列が与えられた例と同じである必要はありません。したがって、replaceは使用できません。
2015

ここにパフォーマンスの比較があります。文字列置換メソッドは、内部で正規表現を使用します。stackoverflow.com/questions/16228992/...
イゴールVuković


7

StringBuilderを使用すると、次の方法で置き換えることができます。

StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");

6

最初に、元の文字列をトークン "("を使用して文字列の配列に分割します。出力配列の位置0にある文字列は、必要なものです。

String[] output = originalString.split(" (");

String result = output[0];

5

Stringオブジェクトのsubstring()メソッドを使用する必要があります。

コード例は次のとおりです。

仮定:ここでは、最初の括弧まで文字列を取得したいと仮定しています。

String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);

2

commonslangのStringUtilsを使用する

nullソース文字列はnullを返します。空( "")のソース文字列は、空の文字列を返します。nullの削除文字列は、ソース文字列を返します。空( "")の削除文字列は、ソース文字列を返します。

String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"

1
// Java program to remove a substring from a string
public class RemoveSubString {

    public static void main(String[] args) {
        String master = "1,2,3,4,5";
        String to_remove="3,";

        String new_string = master.replace(to_remove, "");
        // the above line replaces the t_remove string with blank string in master

        System.out.println(master);
        System.out.println(new_string);

    }
}

1

「(」の後のすべてを削除する必要がある場合は、これを試してください。括弧がない場合は何もしません。

StringUtils.substringBefore(str, "(");

末尾の括弧の後にコンテンツがある可能性がある場合は、これを試してください。

String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")"); 

エンドスペースを削除するには、 str.trim()

Apache StringUtils関数は、null、空、およびマッチセーフではありません


良い解決策!!
スミットシュクラ

0

replace文字列を修正するために使用できます。以下は、「(」の前のすべてを返し、先頭と末尾の空白もすべて削除します。文字列が「(」で始まる場合は、そのままにします。

str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched

これはJavaでは機能しないようです。ECMAscriptの派生物である可能性があります。このコードをJavaのように機能させる方法はありますか?
1111161171159459134 2015

0

Kotlinソリューション

末尾から特定の文字列を削除する場合は、 removeSuffixドキュメント)を使用してください

var text = "one(two"
text = text.removeSuffix("(two") // "one"

文字列にサフィックスが存在しない場合は、元のサフィックスが返されます

var text = "one(three"
text = text.removeSuffix("(two") // "one(three"

文字の後に削除したい場合は、

// Each results in "one"

text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")

また、チェックアウトすることができremovePrefixremoveRangeremoveSurrounding、とreplaceAfterLast類似しています

完全なリストはここにある:ドキュメント

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.