Convert a char to a string in Kotlin
This article explores different ways to convert a primitive char value to its equivalent String in Kotlin.
1. Using toString() function
The standard approach to convert a char to a string in Kotlin is with the toString() function.
|
1 2 3 4 5 6 7 |
fun main() { val ch = 'A' val str: String = ch.toString() println(str) // A } |
2. Using String Concatenation
Alternatively, you can concatenate the given char with an empty string to get a string object.
|
1 2 3 4 5 6 7 |
fun main() { val ch = 'A' val str: String = "" + ch println(str) // A } |
You can also use the plus() function, which is effectively the same as using the + operator. It can accept character or any other datatype value.
|
1 2 3 4 5 6 7 |
fun main() { val ch = 'A' val str: String = "".plus(ch) println(str) // A } |
3. Using String Constructor
The idea is to wrap the specified character inside a character array and then pass the array to the String constructor. The String constructor converts the characters in the specified array to a string.
|
1 2 3 4 5 6 7 |
fun main() { val ch = 'A' val str: String = String(charArrayOf(ch)) println(str) // A } |
4. Using String.format() function
Finally, you can use the String.format() function that returns a formatted string from the specified char arguments.
|
1 2 3 4 5 6 7 |
fun main() { val ch = 'A' val str: String = String.format("%c", ch) println(str) // A } |
5. Using String templates
Finally, you can use String templates to convert a char to a string. It typically consists of a name or an expression, preceded by a dollar sign ($):
|
1 2 3 4 5 6 7 |
fun main() { val c = 'A' val str: String = "$c" println(str) // A } |
That’s all about converting a char to a string 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 :)