35

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.

0

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);
Sign up to request clarification or add additional context in comments.

1 Comment

toCharArray Won't work if String contains emojis. "AB😟🤹👨🏻✅👨👨🏿".toCharArray() will print: [A, B, ?, ?, ?, ?, ?, ?, ?, ?, ✅, ?, ?, ?, ?, ?, ?]
4

You can also use concatToString.

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

Comments

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) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.