繁体   English   中英

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

[英]How to replace multiple substring of a string at one time?

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

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

补充:

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

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

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

如果您只想对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

以上在 Java 1.4 及更高版本中运行。 在 Java 9+ 中,您可以使用StringBuilder而不是StringBuffer ,或者您可以使用replaceAll​()使用 lambda 表达式来实现:

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

String result = Pattern.compile("%(?:(ToolBar)|(Content))%").matcher(s)
        .replaceAll(m -> (m.start(1) != -1 ? "Edit ToolBar" : "made by Paul"));
System.out.println(result); // prints: This Edit ToolBar is a made by Paul

另一个答案中可以看到更动态的版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM