Convert Character array to string in Java

后端 未结 10 1979
野的像风
野的像风 2021-02-05 16:59

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

相关标签:
10条回答
  • 2021-02-05 17:28
    Character[] a = ...
    new String(ArrayUtils.toPrimitive(a));
    

    ArrayUtils is part of Apache Commons Lang.

    0 讨论(0)
  • 2021-02-05 17:28

    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;
    } 
    
    0 讨论(0)
  • 2021-02-05 17:31

    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.

    0 讨论(0)
  • 2021-02-05 17:31

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

    0 讨论(0)
提交回复
热议问题