Replace all substrings that appear in the string – is this more efficient in Java?
I know two ways to replace all substrings in a string
Regular expression (assuming that "sub character substitution" does not include regular expression special characters):
String regex = "substring-to-be-replaced" + "+"; Pattern scriptPattern = Pattern.compile(regex); Matcher matcher = scriptPattern.matcher(originalstring); newstring = matcher.replaceAll("replacement-substring");
String. Replace() method:
newstring = originalstring.replace("substring-to-be-replaced","replacement-substring");
Which of the two is more efficient (why)?
Is there a more effective method than the above two?
Solution
String. Replace () uses regular expressions below
public String replace(CharSequence target,CharSequence replacement) { return Pattern.compile(target.toString(),Pattern.LITERAL) .matcher(this ).replaceAll( Matcher.quoteReplacement(replacement.toString())); }
Given that you can execute the implementation through an array instead of an immutable string class (because string. Replace creates a new string every time it is called) See, for example, StringBuilder replace().
Compiling regular expressions leads to a lot of overhead, which is clear when observing pattern source code Fortunately, Apache is in stringutils An alternative method is provided in replace (), which is very efficient according to the source code (line 3732)