1. Overview

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.

2. Using the String Constructor

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.

3. Using the joinToString() Method

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.

4. Using StringBuilder

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.

5. Conclusion

There are multiple ways to convert a character array to a String. Using the String constructor seems like the easiest to use.

As always, the code samples are available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.