I have a Character
array (not char array) and I want to convert it into a string by combining all the Characters in the array.
I have tried the following f
Actually, if you have Guava, you can use Chars.toArray()
to produce char[]
then simply send that result to String.valueOf()
.
First convert the Character[]
to char[]
, and use String.valueOf(char[])
to get the String as below:
char[] a1 = new char[a.length];
for(int i=0; i<a.length; i++) {
a1[i] = a[i].charValue();
}
String text = String.valueOf(a1);
System.out.println(text);
int length = cArray.length;
String val="";
for (int i = 0; i < length; i++)
val += cArray[i];
System.out.println("String:\t"+val);
Iterate and concatenate approach:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
StringBuilder builder = new StringBuilder();
for (Character c : chars)
builder.append(c);
System.out.println(builder.toString());
Output:
abc
Probably an overkill, but on Java 8 you could do this:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
String value = Arrays.stream(chars)
.map(Object::toString)
.collect( Collectors.joining() );
It's probably slow, but for kicks here is an ugly one-liner that is different than the other approaches -
Arrays.toString(characterArray).replaceAll(", ", "").substring(1, characterArray.length + 1);