Convert a list of characters to a string in Kotlin
This article explores different ways to convert a list of characters to String in Kotlin.
1. Using String Constructor
The standard solution to accumulate specified list characters into a string is with the String constructor.
|
1 2 3 4 5 6 7 |
fun main() { val chars: List<Char> = listOf('T', 'E', 'C', 'H') val string = String(chars.toCharArray()) println(string) // TECH } |
2. Using joinToString() function
We can use the joinToString() function to create a string from a sequence of characters. To create a plain string, pass an empty string as a delimiter to the joinToString() function.
|
1 2 3 4 5 6 7 |
fun main() { val chars: List<Char> = listOf('T', 'E', 'C', 'H') val string = chars.joinToString("") println(string) // TECH } |
3. Using concatToString() function
Alternatively, you can use the concatToString() function, which concatenates characters of the CharArray into a string. Since the input is a list, first convert it to a primitive character array using the toCharArray() function.
|
1 2 3 4 5 6 7 |
fun main() { val chars: List<Char> = listOf('T', 'E', 'C', 'H') val string = chars.toCharArray().concatToString() println(string) // TECH } |
4. Using StringBuilder
Here, the idea to iterate over the specified list characters and append each char to a StringBuilder instance. Finally, make a call to the toString() function to get a string object.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val chars: List<Char> = listOf('T', 'E', 'C', 'H') val sb = StringBuilder() chars.forEach { sb.append(it) } val string = sb.toString() println(string) // TECH } |
That’s all about converting a list of characters 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 :)