Java 字串串接

Java 提供多種方式來連接字串。

+ 運算子

最常用的字串連接方式:

String s1 = "Hello";
String s2 = "World";

String result = s1 + " " + s2;
System.out.println(result);  // "Hello World"

// 連接其他型別
String s = "Age: " + 25;         // "Age: 25"
String s2 = "Price: " + 99.5;    // "Price: 99.5"
String s3 = "Active: " + true;   // "Active: true"

concat()

使用 concat() 方法連接字串:

String s1 = "Hello";
String s2 = "World";

String result = s1.concat(" ").concat(s2);
System.out.println(result);  // "Hello World"

+ vs concat()

String s1 = "Hello";
String s2 = null;

// + 運算子可以處理 null
String r1 = s1 + s2;  // "Hellonull"

// concat() 遇到 null 會拋出例外
// String r2 = s1.concat(s2);  // NullPointerException

repeat() (Java 11+)

重複字串:

String s = "ab";

System.out.println(s.repeat(3));   // "ababab"
System.out.println(s.repeat(0));   // ""
System.out.println("-".repeat(10)); // "----------"

實際應用

// 產生分隔線
String line = "=".repeat(50);
System.out.println(line);

// 縮排
int level = 3;
String indent = "  ".repeat(level);
System.out.println(indent + "內容");

StringBuilder

需要大量字串連接時,使用 StringBuilder 效能較好:

StringBuilder sb = new StringBuilder();

sb.append("Hello");
sb.append(" ");
sb.append("World");

String result = sb.toString();
System.out.println(result);  // "Hello World"

方法鏈

String result = new StringBuilder()
    .append("Hello")
    .append(" ")
    .append("World")
    .toString();

System.out.println(result);  // "Hello World"

更多 StringBuilder 的說明請參考 Java StringBuilder

效能比較

迴圈中連接字串時,+ 運算子效能較差:

// 效能差(每次迴圈都建立新字串)
String result = "";
for (int i = 0; i < 10000; i++) {
    result += i;  // 不建議
}

// 效能好(使用 StringBuilder)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
    sb.append(i);
}
String result2 = sb.toString();

何時使用哪種方式

情況建議方式
簡單的字串連接+ 運算子
迴圈中大量連接StringBuilder
連接陣列/ListString.join()
執行緒安全StringBuffer

其他連接方式

String.join()

String result = String.join(" ", "Hello", "World");
// "Hello World"

String.format()

String result = String.format("%s %s", "Hello", "World");
// "Hello World"

Stream

String result = Stream.of("Hello", "World")
    .collect(Collectors.joining(" "));
// "Hello World"

數字與字串連接

int a = 1, b = 2;

// 字串在前面
System.out.println("" + a + b);    // "12"
System.out.println("Sum: " + a + b); // "Sum: 12"

// 數字在前面
System.out.println(a + b + "");    // "3"
System.out.println(a + b + " is the sum"); // "3 is the sum"

// 使用括號
System.out.println("Sum: " + (a + b)); // "Sum: 3"

null 處理

String s = null;

// + 運算子會轉換成 "null"
System.out.println("Value: " + s);  // "Value: null"

// concat() 會拋出例外
// "Value: ".concat(s);  // NullPointerException

// 使用 Objects.toString()
System.out.println("Value: " + Objects.toString(s, "N/A"));  // "Value: N/A"