00 Votes

Java: Split at point str.split(".") does not work

Question by Guest | 2013-09-24 at 22:14

I have a strange problem in one of my Java programs, which has already cost me hours of time. I'm trying to separate a string at a character, so the classic explode function or exactly the split function in Java.

While this code works perfectly

String str = "1;2;3";
String[] sarr = str.split(";");

inexplicably, the function gives up when using a point as a separator:

String str = "1.2.3";
String[] sarr = str.split(".");

What can I do? Unfortunately, I have to split my string at a dot and I feel bad with a solution with replacing the point with another character that is working before splitting.

ReplyPositiveNegative
2Best Answer2 Votes

The split function in Java expects a regular expression (regex) as a parameter. Therefore, your "." is interpreted as a regular expression and in the world of regular expressions, a point is a special character that can stand for any other character. Therefore, the separation does not work in your case.

To make it work, try it this way:

String str = "1.2.3";
String[] sarr = str.split("\\.");

With the prefix \\ you can escape the point so that it is no longer treated as a special character.
2013-09-24 at 23:32

ReplyPositive Negative
Reply

Related Topics

"G" or "E" sign on my mobile

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.