替换字符串中出现的所有子字符串

编程入门 行业动态 更新时间:2024-10-27 12:37:38
本文介绍了替换字符串中出现的所有子字符串 - 这在Java中更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I know of two ways of replacing all occurrences of substring in a string.

正则表达式方式(假设substring-to-被替换不包括正则表达式特殊字符:

The regex way (assuming "substring-to-be-replaced" doesn't include regex special chars):

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

String.replace()方式:

The String.replace() way:

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

两者中哪一个更有效(以及为什么)?

Which of the two is more efficient (and why)?

是否有比上述两种更有效的方式?

Are there more efficient ways than the above described two?

推荐答案

String.replace() 使用下面的正则表达式。

String.replace() uses regex underneath.

public String replace(CharSequence target, CharSequence replacement) { return Patternpile(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()。

There are given that you operate on an implementation backed e.g., by an array, rather than the immutable String class (since string.replace creates a new string on each invocation). See for instance StringBuilder.replace().

编译正则表达式会产生相当很多的开销,这在观察模式源代码 。幸运的是,Apache在 StringUtils.replace() ,根据源代码(第3732行)非常有效。

Compiling a regex incurs quite alot of overhead which is clear when observing the Pattern source code. Luckily, Apache offers an alternative approach in StringUtils.replace() which according to the source code (line #3732) is quite efficient.

更多推荐

替换字符串中出现的所有子字符串

本文发布于:2023-11-29 23:43:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647990.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!