15

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.

1
  • above is working on char[] :) Commented Oct 31, 2012 at 3:10

10 Answers 10

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

ArrayUtils is part of Apache Commons Lang.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for class I didn't know, I do not understand why such class is not in JDK :-/
It doesn't do anything special particularly. It just creates a char[] of same length and adds the char values. Very basic code. The JDK's job is to focus on the language core and solving not-so-simple, common problems. An open source utility library is the right place for this.
This library should not be included for this solution, but my experience is that I always already have it included for something else anyway!
-1 for "I do not understand why such class is not in JDK" - JDK would blow up if every imaginable utility class being added in new release.
9

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.

Comments

7

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

3 Comments

I would just check this compiles to a StringBuilder, for sizable n .. I think that will happen these days.
thus, for N-length array you'll end up with N strings in the memory
@pst - I'm pretty sure that the JLS doesn't sanction string concatenation optimization across multiple statements.
3

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

Comments

3

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

Comments

3

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() );

3 Comments

Arrays.asList(chars).stream() can be simplified to Arrays.stream(chars)
for big arrays (>10000 elements) much better performance would be using \n char[] chars2 = new char[chars.length]; IntStream.range(0, chars.length).forEach(i -> chars2[i] = chars[i]); String str = new String(chars);
What is the time complexity of this approach?
2

At each index, call the toString method, and concatenate the result to your String s.

Comments

2

how about creating your own method that iterates through the list of Character array then appending each value to your new string.

Something like this.

public String convertToString(Character[] s) {
   String value;

   if (s == null) {
     return null;
   }

   Int length = s.length();
   for (int i = 0; i < length; i++) {
     value += s[i];
   }

   return value;
} 

3 Comments

You are checking s for null after calling length() on it.
Should have noticed that at first as I was aiming to optimize it a bit for good example practice for others. :)
IMO, the null check is misguided. By default, a null argument is due to a programmer's error, and the best way to deal with it is to throw an NPE.
2

Actually, if you have Guava, you can use Chars.toArray() to produce char[] then simply send that result to String.valueOf().

Comments

0
int length = cArray.length;
String val="";
for (int i = 0; i < length; i++)
    val += cArray[i];
System.out.println("String:\t"+val);

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.