Convert Character array to string in Java

后端 未结 10 2011
野的像风
野的像风 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:11

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

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

    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);
    
    0 讨论(0)
  • 2021-02-05 17:19
    int length = cArray.length;
    String val="";
    for (int i = 0; i < length; i++)
        val += cArray[i];
    System.out.println("String:\t"+val);
    
    0 讨论(0)
  • 2021-02-05 17:21

    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

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

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

    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);
    
    0 讨论(0)
提交回复
热议问题