使用StringBuilder替换字符串的所有匹配项?

2022-08-31 11:59:03

是我遗漏了什么,还是StringBuilder缺少与普通String类相同的“用字符串B替换字符串A的所有匹配项”函数?StringBuilder替换函数并不完全相同。有没有办法在不使用普通 String 类生成多个 String 的情况下更有效地执行此操作?


答案 1

好吧,你可以写一个循环:

public static void replaceAll(StringBuilder builder, String from, String to) {
    int index = builder.indexOf(from);
    while (index != -1) {
        builder.replace(index, index + from.length(), to);
        index += to.length(); // Move to the end of the replacement
        index = builder.indexOf(from, index);
    }
}

请注意,在某些情况下,使用可能会更快,从后面工作。我怀疑如果你用一个短字符串替换一个长字符串,情况就是这样 - 所以当你开始时,任何替换都有更少的复制。无论如何,这应该给你一个起点。lastIndexOf


答案 2

您可以使用模式/匹配器。来自 Matcher javadocs:

 Pattern p = Pattern.compile("cat");
 Matcher m = p.matcher("one cat two cats in the yard");
 StringBuffer sb = new StringBuffer();
 while (m.find()) {
     m.appendReplacement(sb, "dog");
 }
 m.appendTail(sb);
 System.out.println(sb.toString());

推荐