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 regexsplit("[.]")
- escaping using character classsplit("\\Q.\\E")
-\Q
and\E
mark area in which regex metacharacters should be treated as simple literalssplit(Pattern.quote("."))
- this method usesPattern.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.