
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: September 7, 2024
In this article, we’ll look at some ways to convert a Kotlin character array to a String.
First, we’ll use the native String constructor. Then, we’ll look at a factory function. Finally, we’ll use the StringBuilder to perform a character array to String conversion.
We can simply use the String constructor to convert a character array:
val charArray = charArrayOf('b', 'a', 'e', 'l')
val convertedString = String(charArray)
Here, we first create a CharArray with the charArrayOf helper function.
We then use the String class’s constructor, which accepts a CharArray. As a result, the array is converted to a String.
We can also use another simple technique to convert a character array to a String. With the Array<Char>.joinToString() method, we can create a String from an initialized character array:
val charArray: Array<Char> = arrayOf('b', 'a', 'e', 'l')
val convertedString = charArray.joinToString()
Here, we create an Array of Char type.
Then, we call the joinToString() factory function and turn the Array into a String.
Another technique we can employ is to use the StringBuilder for the conversion:
val charArray = charArrayOf('b', 'a', 'e', 'l')
val convertedString = StringBuilder().append(charArray).toString()
We call the StringBuilder‘s append() method, which accepts a CharArray.
Subsequently, we call the toString() method, which returns a String.
There are multiple ways to convert a character array to a String. Using the String constructor seems like the easiest to use.