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

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

问题描述

我是否遗漏了某些内容,或者StringBuilder是否缺少与普通String类相同的将所有出现的字符串A替换为字符串B的函数? 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替换所有出现的String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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