Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Character array to string in Java

Tags:

java

string

char

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 for a given Character[] a:

String s = new String(a) //given that a is a Character array

But this does not work since a is not a char array. I would appreciate any help.

like image 312
Aasam Tasaddaq Avatar asked Oct 31 '12 03:10

Aasam Tasaddaq


People also ask

How do I convert a char array to a string in Java?

char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);

Can we convert array to string in Java?

Below are the various methods to convert an Array to String in Java: Arrays. toString() method: Arrays. toString() method is used to return a string representation of the contents of the specified array.

Can we convert array to string?

Convert Array to String. Sometimes we need to convert an array of strings or integers into a string, but unfortunately, there is no direct method to perform this conversion. The default implementation of the toString() method on an array returns something like Ljava. lang.


3 Answers

Character[] a = ...
new String(ArrayUtils.toPrimitive(a));

ArrayUtils is part of Apache Commons Lang.

like image 80
Torious Avatar answered Oct 19 '22 22:10

Torious


The most efficient way to do it is most likely this:

Character[] chars = ...

StringBuilder sb = new StringBuilder(chars.length);
for (Character c : chars)
    sb.append(c.charValue());

String str = sb.toString();

Notes:

  1. Using a StringBuilder avoids creating multiple intermediate strings.
  2. Providing the initial size avoids reallocations.
  3. Using charValue() avoids calling Character.toString() ...

However, I'd probably go with @Torious's elegant answer unless performance was a significant issue.


Incidentally, the JLS says that the compiler is permitted to optimize String concatenation expressions using equivalent StringBuilder code ... but it does not sanction that optimization across multiple statements. Therefore something like this:

    String s = ""
    for (Character c : chars) {
        s += c;
    }

is likely to do lots of separate concatenations, creating (and discarding) lots of intermediate strings.

like image 9
Stephen C Avatar answered Oct 19 '22 22:10

Stephen C


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

like image 7
Juvanis Avatar answered Oct 19 '22 23:10

Juvanis