好了,您可以编写一个循环: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,从背面使用它可能会更快。我怀疑是用短字符串替换长字符串的情况-因此,从一开始,任何替换副本的复制量都会减少。无论如何,这应该给您一个起点。
您可以使用模式 / 匹配器。从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());