Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert CharArray / Array<Char> to a String?

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.

like image 550
Naetmul Avatar asked Jun 27 '17 05:06

Naetmul


People also ask

How do I turn a char variable into a string?

We can convert a char to a string object in java by using the Character. toString() method.

Can we convert array to string in java?

So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.


1 Answers

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); 
like image 130
holi-java Avatar answered Sep 25 '22 07:09

holi-java