試試這個
static String replaceMethod(String original, String toReplace,
String replacedWith) {
for(;;) {
int i = original.indexOf(toReplace);
if (i == -1) {
break;
}
original = original.substring(0, i) + replacedWith + original.substring(i + toReplace.length());
}
return original;
}
或更好,但只是copypaste Apache的StringUtils的方法
public static String replace(String text, String searchString, String replacement, int max) {
if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
int start = 0;
int end = text.indexOf(searchString, start);
if (end == INDEX_NOT_FOUND) {
return text;
}
int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = increase < 0 ? 0 : increase;
increase *= max < 0 ? 16 : max > 64 ? 64 : max;
StringBuilder buf = new StringBuilder(text.length() + increase);
while (end != INDEX_NOT_FOUND) {
buf.append(text.substring(start, end)).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = text.indexOf(searchString, start);
}
buf.append(text.substring(start));
return buf.toString();
}
只需使用'String.replace'。或者使用匹配器和正則表達式(直接替換或使用appendReplacement/appendTail重建)。或者使用其他一次性的'indexOf/substring/split'並手動生成結果。我會堅持'String.replace',除非有一個「好」的理由。 – user2864740
@ user2864740什麼是正確答案?如果你還沒有投票,請選擇幫助你的答案。謝謝。 –