You need to first understand why returned array contains an empty first element. When you split a string on a delimiter that occurs at index 0
, it will also split on that delimiter. Now the left side of the delimiter is an empty string, which is what gets stored at index 0
of the array.
So, the following code, will give the first array element as empty string:
"#ab#c".split("#"); // ["", "ab", "c"]
However, if #
was not the first character of the string, you wouldn't have got the empty string at index 0.
Now, if you don't want the empty string as first element, you just need to avoid splitting on first #
. How would you do that? Just ensure that #
you are splitting on is not at the beginning of the string - ^
, by using negative look-behind:
"#ab#c".split("(?<!^)#"); // ["ab", "c"]
This regex splits on #
when it is not preceded by the beginning of the string (?<!^)
. ^
denote the beginning of the string, and (?<!...)
denote negative look-behind.
So, now your delimiter is an empty string itself. Remember, a string contains an empty string before every character, and after the last character too. So, simply splitting on empty string, will split on the delimiter which is before the first character. You rather need to split on empty string, except the one at the beginning. Replacing #
with empty string:
"abc".split("(?<!^)"); // ["a", "b", "c"]
Similarly the negative look-ahead works - (?!^)
, but IMO, the negative look-behind is more intuitive here.
Of course, if you just want to break the string into a character array, you can just use String#toCharArray()
method.