gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:43 24 4
gpt4 key购买 nike

我知道有两种方法可以替换字符串中所有 次出现的子字符串。

正则表达式方式(假设“substring-to-be-replaced”不包括正则表达式特殊字符):

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 在每个上创建一个 new 字符串调用)。参见例如 StringBuilder.replace() .

编译正则表达式会产生相当很多的开销,这在观察 Pattern source code 时很明显。 .幸运的是,Apache 在 StringUtils.replace() 中提供了另一种方法根据source code (第 3732 行)非常有效。

关于java - 替换字符串中所有出现的子字符串 - 这在 Java 中更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5407592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com