在Java中,String
類(lèi)提供了多種字符串拼接的方法。以下是一些常用的字符串拼接技巧:
+
操作符: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
類(lèi):StringBuilder
類(lèi)是一個(gè)可變的字符串類(lèi),適用于大量字符串拼接的場(chǎng)景。它提供了append()
方法來(lái)拼接字符串。
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()
方法允許你使用格式化字符串來(lái)拼接字符串。
String str1 = "Hello";
String str2 = "World";
String result = String.format("%s %s", str1, str2);
System.out.println(result); // 輸出 "Hello World"
${}
占位符(僅適用于String.format()
和MessageFormat
類(lèi)):String str1 = "Hello";
String str2 = "World";
String result = String.format("%s %s", str1, str2);
System.out.println(result); // 輸出 "Hello World"
// 使用MessageFormat類(lèi)
MessageFormat formatter = new MessageFormat("{0} {1}");
result = formatter.format(new Object[]{str1, str2});
System.out.println(result); // 輸出 "Hello World"
總結(jié):
+
操作符或concat()
方法。StringBuilder
類(lèi)。String.format()
方法或MessageFormat
類(lèi)。