I am trying the following code:-
String x = "asdfg/dgws";
x.replaceAll("/", "\\");
But this is failing. This is giving 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 am not able to figure out why this exception is coming?
String.replaceAllends up using (or being equivalent to using)Matcher.replaceAll, which includes this in the documentation:While you could escape the backslash as per AlexR’s answer, I would strongly recommend that you use
replaceinstead:That’s a lot clearer, IMO – don’t use
replaceAllunless you’re really trying to express a pattern via regular expressions.Also note that as written your code would be a no-op anyway; strings are immutable in Java, so the
replaceAllmethod (and similar ones) return a reference to a new string with the modificiations made.