Convert a string to a character array in Kotlin
This article explores different ways to convert a string to a character array in Kotlin.
1. Using toCharArray() function
The standard solution to convert a string to a character array is with the toCharArray() function.
|
1 2 3 4 5 6 7 8 9 10 |
fun toCharacterArray(str: String): CharArray { return str.toCharArray() } fun main() { val str = "KOTLIN" val chars: CharArray = toCharacterArray(str) println(chars.contentToString()) // [K, O, T, L, I, N] } |
The toCharArray() function returns a CharArray containing characters in the string. If you need a typed array, make an extra call to the toTypedArray() function.
|
1 2 3 4 5 6 7 8 9 10 |
fun toCharacterArray(str: String): Array<Char> { return str.toCharArray().toTypedArray() } fun main() { val str = "KOTLIN" val chars: Array<Char> = toCharacterArray(str) println(chars.contentToString()) // [K, O, T, L, I, N] } |
2. Using for loop
You can also use a for-loop to read the characters in the string and assign them to a Char Array.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun toCharacterArray(str: String): Array<Char?> { val chars = arrayOfNulls<Char>(str.length) for (i in str.indices) chars[i] = str[i] return chars } fun main() { val str = "KOTLIN" val chars = toCharacterArray(str) println(chars.contentToString()) // [K, O, T, L, I, N] } |
That’s all about converting a string to the Character array 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 :)