Added String together in Java?
How can I 开发者_如何转开发add two strings before and after a single char?
Try this:
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello2";
char c = 'a';
System.out.println(str1 + c + str2);
}
}
How about
String string3 = string1 + Character.toString(c) + string2;
Just so you know, this is called string concatenation.
The generally accepted way to concatenate Strings, characters, and really anything else in Java, is StringBuilder.
StringBuilder builder = new StringBuilder();
builder.append("foo");
builder.append('&');
builder.append("bar");
System.out.println(builder.toString()); // foo&bar
If you're using a pre-1.5 JDK, or you require thread-safety, you would use StringBuffer instead.
Assuming the character is in a variable named c
, and the strings are in variables named before
and after
:
String string=before+new String(new char[] { c })+after;
Alternate way:
String combinedString = beforeString.concat(String.valueOf(c)).concat(afterString);
string concatenation using .concat method supposedly gives faster results than the concatenation operator.
I'm pretty sure this has to do with the conversion of string + string being translated into something like StringBuffer s; s.add(string1); s.add(string2); return s.toString();
by using .concat this is avoided.
精彩评论