I was just experimenting with the `String.split` f...
# getting-started
j
I was just experimenting with the
String.split
functionality and came across this situation which made me curious. I found that running this:
"hello".split("")
produces this
["", "h", "e", "l", "l", "o", ""]
. I didn’t expect for there to be empty strings on the start and end of the returned list only that the list would be made up of each character from the original string. To clarify, I’m not asking about the best way to iterate characters in a string or how to get them into a list, just curious about the implementation of
split
with an empty separator and why the empty strings were appended to each end of the resulting list?
v
It is the same with a non-empty separator.
":h:e:l:l:o:".split(":")
should give you the same result.
j
Hmm, interesting. I guess I just didn’t think of there being empty space on either end of the string and only thought of it being between the characters. I was thinking of it as if the string was formatted
"h:e:l:l:o".split(":")
where the only “empty” spaces are between the characters but I think that makes sense that technically there is empty space before and after each character including the first and last characters.
👍 1
k
Note that
java.lang.String.split
behaves the way you expected.
👍 1
🤔 1