阅读量:157
在Java中,String类提供了多种字符串拼接的方法。以下是一些常用的字符串拼接技巧:
- 使用
+操作符:
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2;
System.out.println(result); // 输出 "Hello World"
- 使用
concat()方法:
String str1 = "Hello";
String str2 = "World";
String result = str1.concat(" ").concat(str2);
System.out.println(result); // 输出 "Hello World"
- 使用
StringBuilder类:
StringBuilder类是一个可变的字符串类,适用于大量字符串拼接的场景。它提供了append()方法来拼接字符串。
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
System.out.println(result); // 输出 "Hello World"
- 使用
String.format()方法:
String.format()方法允许你使用格式化字符串来拼接字符串。
String str1 = "Hello";
String str2 = "World";
String result = String.format("%s %s", str1, str2);
System.out.println(result); // 输出 "Hello World"
- 使用
${}占位符(仅适用于String.format()和MessageFormat类):
String str1 = "Hello";
String str2 = "World";
String result = String.format("%s %s", str1, str2);
System.out.println(result); // 输出 "Hello World"
// 使用MessageFormat类
MessageFormat formatter = new MessageFormat("{0} {1}");
result = formatter.format(new Object[]{str1, str2});
System.out.println(result); // 输出 "Hello World"
总结:
- 对于少量字符串拼接,可以使用
+操作符或concat()方法。 - 对于大量字符串拼接,推荐使用
StringBuilder类。 - 如果你需要格式化字符串,可以使用
String.format()方法或MessageFormat类。