Welcome to Srini's blog

Friday, August 27, 2010

Java strings splitting issue

Yesterday I faced an interesting issue with java strings. I have a string values with .(dot) , ex. 127.4.3.2 ,,etc. My aim is to split the string by .(dot), As usual I used the following stmts to do it.

String myStr = "172.5.33.22";
String[] strs = myStr.split(".");
System.out.println("Length : " + strs.length);


But when I run the program the resulte strs length is 0. Then I modified myStr as '172,22,,5,6' and modified split str as ','. its resulting strs length as 4. I wondered why happening this, A quick googling I got solution and its worked. The sol is If you want to slpit the string by .(dot) you need to specify regExp as '\\.'.

The working code is
String myStr = "172.5.33.22";
String[] strs = myStr.split("\\.");
System.out.println("Length : " + strs.length);

Now I got correct strs length.

No comments:

Post a Comment