Last active
July 9, 2022 21:49
-
-
Save ktprezes/9f7e1a33bdb4cb8a814dabad107f10e1 to your computer and use it in GitHub Desktop.
Kotlin - splitting a string into individual characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val string: String = "abcd" | |
val splitString: List<String> = string.map { it.toString() } | |
/* | |
EXPLANATION: | |
A) In Java, the output of the code: | |
String str = "abcd"; | |
String[] splitString = str.split(""); | |
System.out.println(Arrays.toString(splitString)); | |
System.out.println(splitString[0].getClass()); | |
System.out.println(splitString.length); | |
is: | |
[a, b, c, d] // original string is split into _array_ of strings | |
class java.lang.String | |
4 // length of the resulting array | |
B) In Kotlin, the output of the naive-translation-of-java-code: | |
val str = "abcd" | |
val splitString: List<String> = str.split("") | |
println(splitString) | |
println(splitString[0]::class.qualifiedName) | |
println(splitString.size) | |
is: // original string is split into _list_ of strings AND | |
[, a, b, c, d, ] // first and last element of this list are "" (empty strings) | |
kotlin.String | |
6 // length of the resulting list | |
THUS, | |
to get the result similar to the java code, | |
one should use: str.map { it.toString() } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment