Convert a string to a char in Kotlin
This article explores different ways to convert a string containing exactly one character to its equivalent character value in Kotlin.
1. Using first() function
The standard approach to converting a string to a char in Kotlin is to use the first() function, which returns the first index’s element.
|
1 2 3 4 5 6 |
fun main() { val s = "A"; val c: Char = s.first() print(c) } |
2. Using [] operator
Another approach is to use the indexing operator [] on the specified string to retrieve the character value present at the first index.
|
1 2 3 4 5 6 |
fun main() { val s = "A"; val c: Char = s[0] // s.get(0) print(c) } |
3. Using single() function
A string can contain a single character, more than one character, or can be empty. If you need to return a single character and throw an exception if the char sequence is empty or has more than one character, use the single() function.
|
1 2 3 4 5 6 |
fun main() { val s = "A"; val c: Char = s.single() print(c) } |
That’s all about converting a string to a char 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 :)