我知道有两种方法可以替换字符串中所有出现的子字符串.
正则表达式方式(假设"要替换的子字符串"不包括正则表达式特殊字符):
String regex = "substring-to-be-replaced" + "+";
Pattern scriptPattern = Pattern.compile(regex);
Matcher matcher = scriptPattern.matcher(originalstring);
newstring = matcher.replaceAll("replacement-substring");
Run Code Online (Sandbox Code Playgroud)
String.replace()方式:
newstring = originalstring.replace("substring-to-be-replaced", "replacement-substring");
Run Code Online (Sandbox Code Playgroud)
哪两个更有效(以及为什么)?
有没有比上述两种更有效的方法?