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)

Recommended Answers

All 7 Replies

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

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...

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

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

Unless you need to use regular expressions, then use "replace" rather than "replaceAll".

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.........

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.

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

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

coool!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.