33

I have a CharArray whose contents are characters like:

val chars = arrayOf('A', 'B', 'C')

or

val chars = "ABC".toCharArray()

I want to get the string "ABC" from this. How can I do it?

chars.toString() does not work; it works as if chars was a normal integer array.

1

3 Answers 3

62

you can simply using Array#joinToString:

val result: String = chars.joinToString("");

OR convert chars to CharArray:

val result: String = String(chars.toCharArray());

OR declaring a primitive CharArray by using charArrayOf:

val chars = charArrayOf('A', 'B', 'C');
val result: String = String(chars);
1
  • toCharArray Won't work if String contains emojis. "AB😟🤹👨🏻✅👨👨🏿".toCharArray() will print: [A, B, ?, ?, ?, ?, ?, ?, ?, ?, ✅, ?, ?, ?, ?, ?, ?]
    – A. Amini
    Jul 30, 2020 at 11:18
3

You can also use concatToString.

val chars = "ABC".toCharArray()
val result = chars.concatToString()
2

Additionally, the String(chars: CharArray) constructor can be invoked as either

    val ctor: (CharArray) -> String = ::String
    val result = chars.let(ctor)

or

    val result = chars.let { String(it) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.