在Java中,连接字符串可以通过多种方式实现:
使用
+
操作符
:
String str1 = “Hello”;
String str2 = “World”;
String result = str1 + ” ” + str2; // 结果为 “Hello World”
使用
concat()
方法
:
String str1 = “Hello”;
String str2 = “World”;
String result = str1.concat(” “).concat(str2); // 结果为 “Hello World”
使用
StringBuilder
或
StringBuffer
:
StringBuilder sb = new StringBuilder(“Hello”);
sb.append(” “);
sb.append(“World”);
String result = sb.toString(); // 结果为 “Hello World”
StringBuffer
与
StringBuilder
类似,但它是线程安全的。
使用
String.join()
方法
(Java 8及以上版本):
String result = String.join(” “, “Hello”, “World”); // 结果为 “Hello World”
使用
String.format()
方法
:
String result = String.format(“%s %s”, “Hello”, “World”); // 结果为 “Hello World”
使用
String.format()
与
+
组合
:
String result = String.format(“%s %s”, “Hello”, “World”).toUpperCase(); // 结果为 “HELLO WORLD”
使用
StringTemplate
(需要Apache Commons Lang库)
:
String result = String.format(“%s %s”, “Hello”, “World”); // 结果为 “Hello World”
使用
String.format()
与
+
组合
:
String result = String.format(“%s %s”, “Hello”, “World”).toUpperCase(); // 结果为 “HELLO WORLD”
选择哪种方式取决于你的具体需求和Java版本。对于简单的字符串连接,
+
操作符是最直观和简单的方法。对于更复杂的字符串操作,
StringBuilder
或
StringBuffer
提供了更高的性能和灵活性。