`"abc".split("")` splits into a list of Strings `[...
# getting-started
v
"abc".split("")
splits into a list of Strings
[, a, b, c, ]
(5 elements) with an empty string at the beginning and end. Why is it so? And how to split the string into individual letters to the List<String>?
v
Why not? It splits on every occurrence of the separator. The separator is the empty string. So the separator is found at the beginning and the end. To just get a list of strings with one character, you can do
Copy code
"abc".chunked(1)
e
Copy code
"abc".toList() == listOf('a', 'b', 'c')
"abc".map { it.toString(0 } = listOf("a", "b", "c")
(or
chunked(1)
as mentioned)
Java's own String.split has inconsistent behavior when the empty string is matched; Kotlin's is consistent
Copy code
("abc" as java.lang.String).split("".toRegex().toPattern()) == listOf("a", "b", "c", "") // current versions of Java (it has changed!)
"abc".split("".toRegex()) == listOf("", "a", "b", "c", "") // Kotlin
v
toList()
returns list of Chars. But
chunked(1)
is exactly what I need. Thanks guys!
a
@Vitali Plagov hope this might work your scenario : "abc".toList().joinToString("")
v
That would be a no-op, how should that help him? It doesn't give the result he asked for.
k
Why is Kotlin considered "consistent" when an empty string is used as the delimiter? I can see an infinite number of such delimiters between each character of the string, resulting in
["", "", ... "", "a", "", "", ..., "", "b",...]
so why the arbitrary decision of assuming there is just one empty string between each character? You could just as well say there is 0 empty strings between each character (since that is another valid arbitrary choice of the valid range of 0 to infinity).
v
You're becoming a bit polemic, aren't you?
e
between Kotlin's and Java's behavior (which has changed between versions and is currently unbalanced on regexes) which one would you call more consistent?
m
I would simply not allow empty strings as a regex to begin with ­čśŤ. Just slap a
assert(string.size > 0)
on that bad boy and call it a day. Can't have inconsistency if it can't even be. taps forehead
v
Wouldn't help
(?i)
k
How has the Java behaviour changed recently? It seems to have been like this since Java 8. (I don't have any obsolete JDKs so didn't test with anything earlier.) Not saying that Java is consistent, though. I just find it strange that an empty string is accepted as a delimiter without documenting its behaviour.
v
It changed from 7 to 8