2

I want to split a string to single characters. So I do:

"abcd".split("");

But this yields:

["", "a", "b", "c", "d"]

The first empty string is not something I'm used to when doing the same in other languages (e.g. Ruby). What is the logic behind it?

Gadi A
  • 3,449
  • 8
  • 36
  • 54
  • 2
    Same reason: http://stackoverflow.com/questions/145509/why-does-abcd-startswith-return-true – Matt Ball Apr 19 '12 at 17:12
  • 1
    You can use `substring(i, i+1)` or `charAt(i)` or `toCharArray()` to access characters. – khachik Apr 19 '12 at 17:14
  • But why is the empty string added only to the beginning of the array and not everywhere? (especially at the end) – Gadi A Apr 19 '12 at 17:15
  • 3
    There is no empty string at the end because [_"`[String#split(String)]` works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array."_](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29) – Matt Ball Apr 19 '12 at 17:17

1 Answers1

4

Why are you using String.split() for this? You might be better served using String.toCharArray().

I know one will return you an array of Strings while the other will give you an array of chars. Since you want each character separately, I am assuming this doesn't matter to your code.

Colin D
  • 5,641
  • 1
  • 23
  • 35