How to Use toCharArray in Kotlin: Simple Guide
In Kotlin, you can use the
toCharArray() function to convert a String into an array of characters (CharArray). This function returns a new array containing each character of the string in order.Syntax
The toCharArray() function is called on a String object and returns a CharArray containing all characters of the string.
- String.toCharArray(): Converts the string into a character array.
kotlin
val chars: CharArray = "Hello".toCharArray()Example
This example shows how to convert a string to a character array and print each character on a new line.
kotlin
fun main() {
val text = "Kotlin"
val charArray = text.toCharArray()
for (char in charArray) {
println(char)
}
}Output
K
o
t
l
i
n
Common Pitfalls
One common mistake is trying to use toCharArray() on a null string, which causes a NullPointerException. Always ensure the string is not null before calling this function.
Another mistake is confusing toCharArray() with toCharArray(startIndex, endIndex) which does not exist in Kotlin; slicing must be done separately.
kotlin
fun main() {
val nullableText: String? = null
// Wrong: nullableText?.toCharArray() ?: CharArray(0) is safe, but nullableText.toCharArray() throws error
// Correct way:
val safeCharArray = nullableText?.toCharArray() ?: CharArray(0)
println(safeCharArray.size) // prints 0
}Output
0
Quick Reference
| Function | Description |
|---|---|
| toCharArray() | Converts entire string to CharArray |
| nullableString?.toCharArray() ?: CharArray(0) | Safe call to handle null strings |
| string.toCharArray().size | Gets number of characters in string |
Key Takeaways
Use
toCharArray() to convert a Kotlin string into a character array.Always check for null before calling
toCharArray() to avoid errors.The returned
CharArray contains characters in the same order as the string.There is no built-in substring version of
toCharArray(); slice the string first if needed.Iterate over the
CharArray to access individual characters easily.