public String trim()
回傳一個新字串,移除原字串開頭與結尾的空白字元。原字串不變 (String 不可變)。
Unicode 碼點 <= ' ' (U+0020),包含:
\t (U+0009)\n (U+000A)\r (U+000D)String s1 = " Hello World ";
String s2 = s1.trim();
System.out.println("[" + s1 + "]"); // [ Hello World ] 原字串不變
System.out.println("[" + s2 + "]"); // [Hello World] 新字串去除首尾空格
String s3 = "\t\n Test \r\n";
System.out.println("[" + s3.trim() + "]"); // [Test] 移除各類空白
// 中間空白不受影響
String s4 = "A B C";
System.out.println(s4.trim()); // "A B C"
| 誤區 | 正確做法 |
|---|---|
| 以為能移除中間空格 | 用 replaceAll("\\s+", " ") 合併多空格 |
| 以為能移除全形空格 (U+3000) | 用 replaceAll("[\\s\\u3000]+", "") 或 Apache Commons StringUtils.trim() |
| 用於 null 字串 | 先判空或用 Objects.toString(str, "").trim() |
String s = " Hi ";
s.strip(); // 同 trim,但使用 Unicode 空白字元定義 (更嚴謹)
s.stripLeading(); // 僅移除開頭
s.stripTrailing(); // 僅移除結尾
s.isBlank(); // 僅含空白字元 (或空字串) 回傳 true
trim() 會建立新字串物件,高頻呼叫 (如大迴圈) 產生大量暫時物件,增加 GC 壓力。isBlank() 避免建立新字串。