You are not actually getting a leading whitespace element, you are getting a leading empty string, as can be seen from printing the whole array:
System.out.println(java.util.Arrays.toString("1234".split("")));
Output:
[, 1, 2, 3, 4]
The rationale for that behavior is the fact that "1234".indexOf("")
is 0
. I.e., the delimiter string matches at the beginning of the searched string, and thus it creates a split there, giving an empty initial element in the returned array. The delimiter also matches at the end of the string, but you don't get an extra empty element there, because (as the String.split
documentation says) "trailing empty strings will be discarded".
However, the behavior was changed for Java 8. Now the documentation also says:
When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.
(Compare String.split
documentation for Java 7 and Java 8.)
Thus, on Java 8 and above, the output from the above example is:
[1, 2, 3, 4]
For more information about the change, see: Why in Java 8 split sometimes removes empty strings at start of result array?
Anyway, it is overkill to use String.split
in this particular case. The other answers are correct that to get an array of all characters you should use str.toCharArray()
, which is faster and more straightforward. If you really need an array of one-character strings rather than an array of characters, then see: Split string into array of character strings.