java - 在Java中,如何在所有实例中将字符串中多个位置出现的符号替换为另一个符号?

标签 java string replace

我编写了一种方法,用给定字符串中的另一个符号替换给定符号的第一个实例。

我想修改此方法,以便它将用该字符串中给定的新符号替换旧符号的所有实例。

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();
}

最佳答案

只需使用 String.replace 。它完全符合您的要求:

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

<小时/>

有点 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"

关于java - 在Java中,如何在所有实例中将字符串中多个位置出现的符号替换为另一个符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16442595/

相关文章:

C:如何读取多个字符串片段并打印 #of 片段和 #of 字符

GWT 2.0.3 中的 String.split() 方法错误

Javascript替换方法,替换为 "$1"

java - 获取AsyncTask的结果而不阻塞线程

javascript - 如何使用 gremlin 查询将 json 保存为顶点属性值

java - 从包发布的错误通知,无法展开 RemoteViews

python - 将字符串(任意顺序)与大数组中的字符串进行匹配

jquery - 如何使用 Jquery 替换整个 HTML 页面中的占位符?

python - 使用 Numpy 查找给定多个数组值的索引

java - 在java中的多个空格上拆分字符串