如何一次替换字符串的多个子字符串?

时间:2016-07-29 01:46:46

标签: java android

我希望在String中替换两个子字符串,所以我编写以下代码。我认为当S是一个巨大的字符串时,我的代码效率太低了。

我可以一次替换字符串的多个子字符串吗?还是有更好的方法来替换字符串?

加了:

我希望找到一种可以快速替换子串的方法!

   String s="This %ToolBar% is a %Content%";

   s=s.replace("%ToolBar%","Edit ToolBar");
   s=s.replace("%Content%","made by Paul");

1 个答案:

答案 0 :(得分:3)

如果您只想对s执行一次搜索,则可以执行自己的indexOf()循环,也可以使用正则表达式替换循环。

以下是使用正则表达式替换循环的示例,该循环使用appendReplacement()appendTail()方法来构建结果。

为了消除进行字符串比较以确定找到哪个关键字的需要,每个关键字都成为一个捕获组,因此可以使用start(int group)快速检查关键字是否存在。

String s = "This %ToolBar% is a %Content%";

StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("%(?:(ToolBar)|(Content))%").matcher(s);
while (m.find()) {
    if (m.start(1) != -1)
        m.appendReplacement(buf, "Edit ToolBar");
    else if (m.start(2) != -1)
        m.appendReplacement(buf, "made by Paul");
}
m.appendTail(buf);
System.out.println(buf.toString()); // prints: This Edit ToolBar is a made by Paul

this other answer中可以看到更具动态性的版本。

相关问题