For example, a string with the following X
String x = "[Kllkklk\\kk\\kllkk]";
To replace the "KK" inside with + +, you can use both methods to get the same result
Replace (charsequence target, charsequence replacement)--x.replace ("KK", "+ +")
ReplaceAll (string regex, string replacement)--x.replaceall ("KK", "+ +")
There is no difference between the two functions, and the following "\ \" In the string is replaced with "+ +"
System.out.println (x.replace ("\ \", "+ +")); No problem
System.out.println (X.replaceall ("\ \", "+ +")); Error java.util.regex.PatternSyntaxException
It can be seen that there is a difference when replacing with an escape character. The ReplaceAll parameter is the regex, which is the regular expression. First, it will be escaped, so error.
If you use System.out.println (X.replaceall ("\\\\", "+ +"), you are done.
So what is the choice of the function when using normal string substitution?
String x = "[Kllkklk\\kk\\kllkk]";
String tmp;
System.out.println (X.replace ("[", "#"). Replace ("]", "#");
System.out.println (New Date (). GetTime ());
for (int i =0;i<1000000;i++)
Tmp=x.replace ("KK", "--");
System.out.println (New Date (). GetTime ());
for (int i =0;i<1000000;i++)
Tmp=x.replaceall ("KK", "+ +");
System.out.println (New Date (). GetTime ());
Test results:
1312424571937
1312424574531
1312424576671
It is faster to test the ReplaceAll function. See source found, replace function inside still use ReplaceAll function.
General principle: The Replace function is recommended when a string cannot determine whether an escape character is available and does not need to be escaped
Otherwise, use the ReplaceAll function