java – String. Error in replaceall() function
•
Java
I'm trying the following code: –
String x = "asdfg/dgws"; x.replaceAll("/","\\");
But it was a failure This gave me the following error message: –
Exception in thread "main" java.lang.Stringindexoutofboundsexception: String index out of range: 1 at java.lang.String.charAt(UnkNown Source) at java.util.regex.Matcher.appendReplacement(UnkNown Source) at java.util.regex.Matcher.replaceAll(UnkNown Source) at java.lang.String.replaceAll(UnkNown Source) at com.jai.SecLargest.main(SecLargest.java:13)
I can't figure out why this anomaly happened?
Solution
String. Replaceall end use (or equivalent) matcher Replaceall, which contains the following:
Although you can avoid backslashes based on Alex R's answers, I strongly recommend that you use substitution:
String y = x.replace('/','\\');
More clearly, IMO – don't use replaceall unless you really try to express patterns through regular expressions
Also note that there is no operation when writing code; Strings are immutable in Java, so the replaceall method (and similar methods) returns a reference to a new string with modifications
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码