Concatenate chars to form String in java

后端 未结 6 884
[愿得一人]
[愿得一人] 2020-12-15 22:31

Is there a way to concatenate char to form a String in Java?

Example:

String str;
Char a, b, c;
a = \'i\';
b = \'c\';
c = \         


        
相关标签:
6条回答
  • 2020-12-15 23:18

    Use StringBuilder:

    String str;
    Char a, b, c;
    a = 'i';
    b = 'c';
    c = 'e';
    
    StringBuilder sb = new StringBuilder();
    sb.append(a);
    sb.append(b);
    sb.append(c);
    str = sb.toString();
    

    One-liner:

    new StringBuilder().append(a).append(b).append(c).toString();
    

    Doing ""+a+b+c gives:

    new StringBuilder().append("").append(a).append(b).append(c).toString();
    

    I asked some time ago related question.

    0 讨论(0)
  • 2020-12-15 23:22

    You can use StringBuilder:

        StringBuilder sb = new StringBuilder();
        sb.append('a');
        sb.append('b');
        sb.append('c');
        String str = sb.toString()
    

    Or if you already have the characters, you can pass a character array to the String constructor:

    String str = new String(new char[]{'a', 'b', 'c'});
    
    0 讨论(0)
  • 2020-12-15 23:29

    If the size of the string is fixed, you might find easier to use an array of chars. If you have to do this a lot, it will be a tiny bit faster too.

    char[] chars = new char[3];
    chars[0] = 'i';
    chars[1] = 'c';
    chars[2] = 'e';
    return new String(chars);
    

    Also, I noticed in your original question, you use the Char class. If your chars are not nullable, it is better to use the lowercase char type.

    0 讨论(0)
  • 2020-12-15 23:30

    Use str = ""+a+b+c;

    Here the first + is String concat, so the result will be a String. Note where the "" lies is important.

    Or (maybe) better, use a StringBuilder.

    0 讨论(0)
  • 2020-12-15 23:31

    Try this:

     str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c);
    

    Output:

    ice
    
    0 讨论(0)
  • Use the Character.toString(char) method.

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