Convert a string to a list of characters in Kotlin
This article explores different ways to convert a string to a list of characters in Kotlin.
1. Using toList() function
The standard solution to convert a string to a list of characters in Kotlin is with the toList() function.
|
1 2 3 4 5 6 7 |
fun main() { val string = "Kotlin" val chars: List<Char> = string.toList() println(chars) // [K, o, t, l, i, n] } |
To get a mutable list, you can use the toMutableList() function:
|
1 2 3 4 5 6 7 |
fun main() { val string = "Kotlin" val chars: MutableList<Char> = string.toMutableList() println(chars) // [K, o, t, l, i, n] } |
2. Using foreach Loop
Another solution is to create a new List and add elements to it using a foreach loop.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val string = "Kotlin" val chars: MutableList<Char> = ArrayList() for (ch in string) { chars.add(ch) } println(chars) // [K, o, t, l, i, n] } |
You can also use the forEach() function, as shown below:
|
1 2 3 4 5 6 7 8 |
fun main() { val string = "Kotlin" val chars: MutableList<Char> = ArrayList() string.forEach { chars.add(it) } println(chars) // [K, o, t, l, i, n] } |
Finally, you can use the IntRange with forEach() to directly access each character and add it to the list.
|
1 2 3 4 5 6 7 8 |
fun main() { val string = "Kotlin" val chars: MutableList<Char> = ArrayList() string.indices.forEach { chars.add(string[it]) } println(chars) // [K, o, t, l, i, n] } |
That’s all about converting a string to a list of characters 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 :)