https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jesse Hill

12/03/2021, 4:18 PM
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

Vampire

12/03/2021, 4:41 PM
It is the same with a non-empty separator.
":h:e:l:l:o:".split(":")
should give you the same result.
j

Jesse Hill

12/03/2021, 4:55 PM
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

Klitos Kyriacou

12/03/2021, 4:57 PM
Note that
java.lang.String.split
behaves the way you expected.
👍 1
🤔 1
4 Views