我编写了一种方法,用给定字符串中的另一个符号替换给定符号的第一个实例。
我想修改此方法,以便它将用该字符串中给定的新符号替换旧符号的所有实例。
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/