Replace and replaceall are commonly used substitution characters in Java, and they differ in the following ways:
1 The parameters of Replace are char and charsequence, that is, can support the replacement of characters , but also support the replacement of strings (charsequence that is, the meaning of the string sequence, in other words, the string);
2 The ReplaceAll parameter is regex, that is, based on the substitution of regular expressions , for example, you can replace all numeric characters of a string with asterisks by ReplaceAll ("\\d", "*");
The same point: all are replaced, that is, a character or string in the source string is all replaced by the specified character or string, if you want to replace the first occurrence, you can use Replacefirst (), this method is also based on the substitution of regular expressions, But unlike ReplaceAll (), only the first occurrence of the string is replaced;
In addition, if the parameter data used by ReplaceAll () and Replacefirst () is not based on a regular expression, the effect of the replace () replacement string is the same, that is, both support string manipulation;
Another note: The contents of the source string have not changed since the substitution operation was performed.
Examples are as follows:
string src = new string ("ab43a2c43d");
System.out.println (Src.replace ("3", "F")); =>ab4f2c4fd.
System.out.println (Src.replace (' 3 ', ' f ')); =>ab4f2c4fd.
System.out.println (Src.replaceall ("\\d", "F")); =>abffafcffd.
System.out.println (Src.replaceall ("A", "F")); =>fb43fc23d.
System.out.println (Src.replacefirst ("\\d," F ")" =>abf32c43d System.out.println ("
4", "H") ); =>abh32c43d.
How to replace "\" in a string with "\":
String Msgin;
String msgout;
Msgout=msgin.replaceall ("\\\\", "\\\\\\\\");
Reason:
' \ ' is an escape character in Java, so it takes two to represent one. For example, System.out.println ("\"), only one "\" is printed. But ' \ ' is also an escape character in a regular expression (the ReplaceAll argument is a regular expression) and requires two delegates. So:\\\\ is converted to \\,\\ by Java and converted to \ by regular expressions.
Same
CODE: \\\\\\\\
Java: \\\\
Regex: \
Several ways to replace the '/' in a string with a ' \ ':
msgout= Msgin.replaceall ("/", "\\\\");
msgout= msgin.replace ("/", "\ \");
msgout= msgin.replace ('/', ' \ n ');
The different points of replace () and ReplaceAll () in Java are distinguished by examples, and we hope this article can help us to learn.