Question

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
Was it helpful?

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.

OTHER TIPS

Your condition is

for(int i = dateCells.length; i < 0; i--){

It starts at 3 and runs while your counter is less than 0. Which it never is.

Obvious solution: either use i > 0 or change it up to loop from 0 to 3.

Additionally: don't forget to escape the dot which is a special regex character. Escaping is done through a backslash (\) but since that backslash is also a special character, you have to escape it as well.

End result:

.split("\\.")

Additionally, you need to escape . when splitting on it, because String.split() treats . as a regex.

public class Foo{
    public static void main(String[] args) {
        String hi = "hello.world.good.bye";
        String[] parts = hi.split("\\.");
        for (int i = 0;i < parts.length; i++)
            System.out.println(parts[i]);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top