replace and replaceAll are commonly used methods of replacing characters in JAVA. Their differences are:
1) The parameters of replace are char and CharSequence, which can support character replacement and string replacement (CharSequence means string sequence, to put it bluntly, string);
2) The parameter of replaceAll is regex, that is, a replacement based on a regular expression. For example, all numeric characters of a string can be replaced by replaceAll("//d", "*");
Similarities: all replace all characters or strings in the source string with specified characters or strings. If you only want to replace the first occurrence, you can use replaceFirst(), and this method is also Replacement based on rule expressions, but unlike replaceAll(), only replaces the first occurrence of strings;
In addition, if the parameter data used by replaceAll() and replaceFirst() is not based on a regular expression, the effect of replacing the string is the same as replace(), that is, both of them also support string operations;
Another note: After performing the replacement operation, the content of the source string has not changed.
As an example:
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"));=>abffaffcffd. System.out.println(src.replaceAll("a"," f"));=>fb43fc23d. System.out.println(src.replaceFirst("//d,"f"));=>abf32c43d System.out.println(src.replaceFirst("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 two need to represent one. For example, System.out.println( "//" ); only one "/" is printed. However, '/' is also an escape character in a regular expression (the parameter of replaceAll is the regular expression), and two need to be used to represent one. So: /// is converted to // by java, and // is converted to / by regular expression.
same
CODE:////////
Java:////
Regex: //
Several ways to replace '/' in a string with '/':
msgOut= msgIn.replaceAll("/", "////"); msgOut= msgIn.replace("/", "//"); msgOut= msgIn.replace('/', '//');The differences between replace() and replaceAll() in Java are distinguished through examples. I hope this article will be helpful to everyone's learning.