0

Why this code fails.... ?

String a = "abcd/dgws";
a.replaceAll("/", "\\");

it results in ......

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:558)
at java.util.regex.Matcher.appendReplacement(Matcher.java:696)
at java.util.regex.Matcher.replaceAll(Matcher.java:806)
at java.lang.String.replaceAll(String.java:2000)

5
Contributors
7
Replies
9
Views
6 Years
Discussion Span
Last Post by sawant_nitesh
0

Hi sawant_nitesh,

In literal Java strings the backslash is an escape character.

In regular expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash. This regular expression as a Java string, becomes "\\\\". so 4 backslashes to match a single one.

SO try using the 4 backslashes and execute the program...

0

1. a.replaceAll("/", "\\\\b");
2. a.replaceAll("/", "\\\\");

Both of these could not solve my problem.........

0

The replaceAll() method returns a new modified String, instead of the old String.
So assign the new String to some String variable.

String a = "abcd/defg"
String b = a.replaceAll("/", "\\\\");

Now b is the modified String.

1. a.replaceAll("/", "\\\\b");
2. a.replaceAll("/", "\\\\");

Both of these could not solve my problem.........

0

Actually as String is immutabale, any operation on String will return a new String.

The replaceAll() method returns a new modified String, instead of the old String.
So assign the new String to some String variable.

String a = "abcd/defg"
String b = a.replaceAll("/", "\\\\");

Now b is the modified String.

0

Oh yes... strings are immutable...
that worked..

1. String a = "abcd/defg"
2. String b = a.replaceAll("/", "\\\\");

coool!!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.