Wednesday, June 29, 2011

Beware of String functions - replaceAll and replace et. al

I was going through replaceAll function. I had following string:
String str = "com.vaani.src.dynamic.CompilationHelloWorld";

I had to replace all dot's with /.So I tried

But what I was getting was,that my string converted to - //////////////////////////////////////////////////////////////////////////////////////

The reason is simple. It was using regex, so dot(.) means replace all with something, here /.
So I solved it using \\ before dot:

Another solution is that because I am using character only, so why not use '' quotes rather than "", ie:
you can do following:

We discussed something similar here as well.

No comments:

Post a Comment