在java中连接字符以形成字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16282368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenate chars to form String in java
提问by Guest
Is there a way to concatenate char
to form a String
in Java?
有没有办法在Java中连接char
以形成a String
?
Example:
例子:
String str;
Char a, b, c;
a = 'i';
b = 'c';
c = 'e';
str = a + b + c; // thus str = "ice";
采纳答案by Adam Stelmaszczyk
Use StringBuilder
:
使用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:
做""+a+b+c
给:
new StringBuilder().append("").append(a).append(b).append(c).toString();
I asked some time ago related question.
我前段时间问过相关问题。
回答by Jias
Use the Character.toString(char)
method.
使用Character.toString(char)
方法。
回答by zw324
Use str = ""+a+b+c;
用 str = ""+a+b+c;
Here the first +
is String
concat, so the result will be a String
. Note where the ""
lies is important.
这里第一个+
是String
concat,所以结果将是一个String
. 注意""
谎言在哪里很重要。
Or (maybe) better, use a StringBuilder
.
或者(也许)更好,使用StringBuilder
.
回答by Achintya Jha
Try this:
尝试这个:
str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c);
Output:
输出:
ice
回答by bdkosher
You can use StringBuilder:
您可以使用 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 构造函数:
String str = new String(new char[]{'a', 'b', 'c'});
回答by Pascal Ganaye
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 Charclass. If your chars are not nullable, it is better to use the lowercase chartype.
另外,我在您的原始问题中注意到,您使用了Char类。如果您的字符不可为空,最好使用小写字符类型。