Convert a comma-separated string to a list in Kotlin
This article explores different ways to convert a comma-separated string to a list in Kotlin.
The standard way to split a Kotlin string is with the split() function. We can use the split() function to convert the comma-separated string to a list in the following ways:
1. Using listOf() function
The idea is to split the string with the split() function and pass the resultant array to the listOf function to get a new list.
|
1 2 3 4 5 6 |
fun main() { val str = "A,B,C,D" val list: List<String> = listOf(*str.split(",").toTypedArray()) println(list) // [A, B, C, D] } |
2. Using toList() function
Another good solution is to directly call the toList() function after splitting the array with the split() function.
|
1 2 3 4 5 6 |
fun main() { val str = "A,B,C,D" val list: List<String> = str.split(",").toList() println(list) // [A, B, C, D] } |
3. Using Pattern.compile() function
Finally, you can split the string using the split() function around the matches of a pattern. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 9 |
import java.util.regex.Pattern fun main() { val str = "A,B,C,D" val list: List<String> = Pattern.compile(",").split(str).toList() println(list) // [A, B, C, D] } |
That’s all about converting a comma-separated string to 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 :)