0

特定のシンボルの最初のインスタンスを特定の文字列内の別のシンボルに置き換えるメソッドを作成しました。

このメソッドを変更して、古いシンボルのすべてのインスタンスをその文字列内の指定された新しいシンボルに置き換えるようにします。

public static String myReplace(String origString, String oldValue, String newValue) {
    char[] chars = origString.toCharArray();
    char[] charsNewValue = newValue.toCharArray();

    StringBuffer sb = new StringBuffer();

    int startPos = origString.indexOf(oldValue);
    int endPos = startPos + oldValue.length();
    int lengthOfString = origString.length();
    if (startPos != -1) {
        for (int i = 0; i < startPos; i++)
            sb.append(chars[i]);
        for (int i = 0; i < newValue.length(); i++)
            sb.append(charsNewValue[i]);
        for (int i = endPos; i < lengthOfString; i++) 
            sb.append(chars[i]);
    } 
    else 
        return toReplaceInto;
    return sb.toString();
}
4

2 に答える 2

1

を使用するだけString.replaceです。それはあなたが求めたことを正確に行います:

リテラル ターゲット シーケンスに一致するこの文字列の各部分文字列を、指定されたリテラル置換シーケンスに置き換えます。


少しOTですが、最初の一致だけを置き換える方法は、必要以上に複雑です。

private static String replaceOne(String str, String find, String replace) {
    int index = str.indexOf(find);
    if (index >= 0)
    {
        return str.substring(0, index) + replace + str.substring(index + find.length());
    }
    return str;
}

テスト:

System.out.println(replaceOne("find xxx find", "find", "REP")); // "REP xxx find"
System.out.println(replaceOne("xxx xxx find", "find", "REP"));  // "xxx xxx REP"
System.out.println(replaceOne("xxx find xxx", "find", "REP"));  // "xxx REP xxx"
System.out.println(replaceOne("xxx xxx xxx", "find", "REP"));   // "xxx xxx xxx"
于 2013-05-08T13:59:45.597 に答える
0

次のように置換メソッドを使用できます。

origString = origString.replace(oldValue, newValue);
于 2013-05-08T14:10:56.240 に答える