加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

替换字符串中所有出现的子字符串 – 这在Java中更有效率?

发布时间:2020-12-14 05:04:32 所属栏目:Java 来源:网络整理
导读:我知道在字符串中替换所有出现的子字符串的两种方法. 正则表达式(假设“子字符替换”不包括正则表达式特殊字符): String regex = "substring-to-be-replaced" + "+";Pattern scriptPattern = Pattern.compile(regex);Matcher matcher = scriptPattern.match
我知道在字符串中替换所有出现的子字符串的两种方法.

正则表达式(假设“子字符替换”不包括正则表达式特殊字符):

String regex = "substring-to-be-replaced" + "+";
Pattern scriptPattern = Pattern.compile(regex);
Matcher matcher = scriptPattern.matcher(originalstring);
newstring = matcher.replaceAll("replacement-substring");

String.replace()方式:

newstring = originalstring.replace("substring-to-be-replaced","replacement-substring");

两个中哪一个更有效率(为什么)?

有比上述两种更有效的方法吗?

解决方法

String.replace()在下面使用正则表达式.
public String replace(CharSequence target,CharSequence replacement) {
      return Pattern.compile(target.toString(),Pattern.LITERAL)
             .matcher(this ).replaceAll(
               Matcher.quoteReplacement(replacement.toString()));
  }

Are there more efficient ways than the above described two?

给定的是,您可以通过数组来执行实现,而不是不可变的String类(由于string.replace在每次调用时都会创建一个新的字符串).参见例如StringBuilder.replace().

编译正则表达式导致了很多开销,这在观察Pattern source code时是很清楚的.幸运的是,Apache在StringUtils.replace()中提供了一种替代方法,根据source code(第3732行),效率非常高.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读