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 回答