Concatenate chars to form String in java

2020-02-09 08:26发布

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 = 'e';

str = a + b + c; // thus str = "ice";

标签: java
5条回答
仙女界的扛把子
2楼-- · 2020-02-09 08:55

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'});
查看更多
家丑人穷心不美
3楼-- · 2020-02-09 08:56

Try this:

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

Output:

ice
查看更多
倾城 Initia
4楼-- · 2020-02-09 09:01

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.

查看更多
等我变得足够好
5楼-- · 2020-02-09 09:01

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.

查看更多
啃猪蹄的小仙女
6楼-- · 2020-02-09 09:13

Use the Character.toString(char) method.

查看更多
登录 后发表回答