Search code examples
javastringstringbuilder

String.split on dot doesn't work as expected


I have a string = 12.05.2014

And I am trying to use split by "." but it is returning empty array for some reason.

System.out.println(newDate);
System.out.println(newDate.length());
String [] dateCells = newDate.split(".");

StringBuilder sBuilder = new StringBuilder();
sBuilder.append(dateCells[2]).append(dateCells[0]).append(dateCells[1]);
System.out.println(sBuilder.toString());

The output is:

12.05.2014
10
            //empty line

Solution

  • split uses regex and in regex . means "any character beside line separators".

    So you split on each character creating array full of empty elements like

    "foo".split(".")
    

    would at first create ["","","",""], but since split also trails empty elements placed at the end of array you would get empty array []. Trailing last empty strings can be turned off with overloaded version of split split(regex,limit) by passing negative value as limit.

    To solve this problem you need to escape .. To do this you can use for instance

    • split("\\.") - standard escape in regex
    • split("[.]") - escaping using character class
    • split("\\Q.\\E") - \Q and \E mark area in which regex metacharacters should be treated as simple literals
    • split(Pattern.quote(".")) - this method uses Pattern.LITERAL flag inside regex compiler to point that metacharacters used in regex are simple literals without any special meaning

    Another problem would be condition in your for loop but more about it in Jeroens answer.