Convert a character array to a string in Kotlin
This article explores different ways to convert a character array to a string in Kotlin.
1. Using String Constructor
The standard solution to convert characters of the specified array into a string is using the String constructor.
|
1 2 3 4 5 6 |
fun main() { val chars = charArrayOf('T', 'e', 'c', 'h') val str = String(chars) println(str) // Tech } |
Additionally, the String constructor can be invoked as:
|
1 2 3 4 5 6 |
fun main() { val chars = charArrayOf('A', 'B', 'C'); val str = chars.let { String(it) } print(str) // ABC } |
2. Using joinToString() function
The joinToString() function is used to create a string from the character Sequence separated by a delimiter. To create a plain string, pass an empty string to the joinToString() function.
|
1 2 3 4 5 6 |
fun main() { val chars = charArrayOf('T', 'e', 'c', 'h') val str = chars.joinToString("") println(str) // Tech } |
3. Using concatToString() function
Alternatively, you can use the concatToString() function, which concatenates characters in the CharArray into a string.
|
1 2 3 4 5 6 |
fun main() { val chars = charArrayOf('T', 'e', 'c', 'h') val str = chars.concatToString() println(str) // Tech } |
4. Using StringBuilder
Here, the idea to iterate over the characters of the specified array and append each char to a StringBuilder instance. Finally, make a call to the toString() function to get a string call.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val chars = charArrayOf('T', 'e', 'c', 'h') val sb = StringBuilder() chars.forEach { sb.append(it) } val str = sb.toString() println(str) // Tech } |
That’s all about converting a character array 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 :)