Split a String into a List in Kotlin
This article explores different ways to split a comma-separated String into a List in Kotlin.
Kotlin doesn’t provide any built-in function to convert a String to a List. We have the split() function, but that split a string into an array. The idea is to call the split() function on the string using the regex \s*,\s* as a delimiter, and convert the resultant string array into a list. The regex \s*,\s* matches with a comma, preceded/followed by zero or more whitespace characters. Here’s the complete code:
|
1 2 3 4 5 |
fun main() { val str = "a, b, c, d" val tokens = listOf(*str.split("\\s*,\\s*".toRegex()).toTypedArray()) println(tokens) } |
Output:
[a, b, c, d]
If we need the mutable instance of the list, consider using the mutableListOf() function over the listOf() function.
|
1 2 3 4 5 |
fun main() { val str = "a, b, c, d" val tokens: List<String> = mutableListOf(*str.split("\\s*,\\s*".toRegex()).toTypedArray()) println(tokens) } |
Output:
[a, b, c, d]
We can directly call the toMutableList() function on the resultant array with the split() function.
|
1 2 3 4 5 |
fun main() { val str = "a, b, c, d" val tokens = str.split("\\s*,\\s*".toRegex()).toMutableList() println(tokens) } |
Output:
[a, b, c, d]
That’s all about splitting a String into a List in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)