Bhaskar
Bhaskar

Reputation: 7523

Converting Character[] to String

What is the best way to convert a Character[] to char[] or a String ?

One way is to manually loop through the Character array presently in a for(char c : CharacterArray) loop , appending to a StringBuilder. StringBuilder seems to accept a Character[] directly also , but is that all to it ?

Upvotes: 2

Views: 2531

Answers (2)

JustinKSU
JustinKSU

Reputation: 4989

I would recommend converting the Character[] to a char[] using a simple loop and then passing it into new String();

    Character[] characters = new Character[128];
    char[] chars = new char[characters.length];
    int length = characters.length;
    for(int i=0; i<length; i++) {
        chars[i] = characters[i].charValue();
    }
    String string = new String(chars);

Another alternative would be to create a StringBuilder and loop through and add each character individually.

    Character[] characters = new Character[128];
    StringBuilder sb = new StringBuilder(characters.length);
    for(Character c : characters) {
        sb.append(c);
    }
    String string = sb.toString();

I have a feeling the first approach might be more efficient, but I'm not sure.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691685

commons-lang has a toPrimitive method, but there's nothing like this in the standard API. The only way is to loop through the array and transform each Character into a char (and decide what to do with null values).

Upvotes: 3

Related Questions