使用 StringBuilder 替换所有出现的字符串? [英] Replace all occurrences of a String using StringBuilder?

查看:94
本文介绍了使用 StringBuilder 替换所有出现的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否遗漏了什么,或者 StringBuilder 是否缺少与普通 String 类相同的用字符串 B 替换所有出现的字符串 A"功能?StringBuilder 替换函数并不完全相同.在不使用普通 String 类生成多个字符串的情况下,有没有更有效的方法?

Am I missing something, or does StringBuilder lack the same "replace all occurrences of a string A with string B" function that the normal String class does? The StringBuilder replace function isn't quite the same. Is there any way to this more efficiently without generating multiple Strings using the normal String class?

推荐答案

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

Well, you can write a loop:

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 从后面工作可能会更快.我怀疑如果您用短字符串替换长字符串,情况就是这样 - 所以当您开始时,任何替换都没有什么可复制的.无论如何,这应该给你一个起点.

Note that in some cases it may be faster to use lastIndexOf, working from the back. I suspect that's the case if you're replacing a long string with a short one - so when you get to the start, any replacements have less to copy. Anyway, this should give you a starting point.

这篇关于使用 StringBuilder 替换所有出现的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆