'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 = "ice";
Solution 1:[1]
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.
Solution 2:[2]
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'});
Solution 3:[3]
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.
Solution 4:[4]
Use the Character.toString(char) method.
Solution 5:[5]
Try this:
str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c);
Output:
ice
Solution 6:[6]
I would use String.format():
char c = 'a';
String s = String.format("%c%c", c, 'b'); // s is "ab"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | zw324 |
| Solution 2 | Adam Stelmaszczyk |
| Solution 3 | Pascal Ganaye |
| Solution 4 | Jias |
| Solution 5 | Achintya Jha |
| Solution 6 | zr0gravity7 |
