Concatenate Chars to Form String in Java
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 =...
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";
7 Answers
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.
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.
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'});
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.
Use the Character.toString(char) method.
Try this:
str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c);
Output:
ice
I would use String.format():
char c = 'a';
String s = String.format("%c%c", c, 'b'); // s is "ab"