溫馨提示×

java多個字符串怎么拼接

小億
83
2024-08-23 02:33:27
欄目: 編程語言

在Java中有幾種方法可以拼接多個字符串:

  1. 使用"+"符號:
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2;
System.out.println(result); // 輸出:Hello World
  1. 使用String.concat()方法:
String str1 = "Hello";
String str2 = "World";
String result = str1.concat(" ").concat(str2);
System.out.println(result); // 輸出:Hello World
  1. 使用StringBuffer或StringBuilder類:
String str1 = "Hello";
String str2 = "World";
StringBuilder sb = new StringBuilder();
sb.append(str1).append(" ").append(str2);
String result = sb.toString();
System.out.println(result); // 輸出:Hello World
  1. 使用String.join()方法:
String str1 = "Hello";
String str2 = "World";
String result = String.join(" ", str1, str2);
System.out.println(result); // 輸出:Hello World

0