在 Java 中去除字串開頭的空白字符(空格、換行 \n、製表符 \t、回車 \r 等),保留中間和結尾空白,可使用手動遍歷或正則表達式實現。
public static String trimLeadingWhitespace(String str) {
if (str == null || str.isEmpty()) return str;
int i = 0;
int len = str.length();
// 遍歷查找第一個非空白字符
while (i < len && Character.isWhitespace(str.charAt(i))) {
i++;
}
return str.substring(i);
}
public static String trimLeadingWhitespaceRegex(String str) {
if (str == null) return null;
// ^ 匹配開頭,\s+ 匹配一個或多個空白字符
return str.replaceFirst("^\\s+", "");
}
// 依賴: org.apache.commons:commons-lang3
import org.apache.commons.lang3.StringUtils;
String result = StringUtils.stripStart(str, null); // null 表示所有空白字符
// 或指定字符集
String result2 = StringUtils.stripStart(str, " \t\n\r");
public static void main(String[] args) {
String test1 = " \n\t Hello World \n";
String test2 = "\n\r\t測試字串";
String test3 = "無前導空白";
String test4 = " "; // 全空白
System.out.println("['" + trimLeadingWhitespace(test1) + "']"); // ['Hello World \n']
System.out.println("['" + trimLeadingWhitespace(test2) + "']"); // ['測試字串']
System.out.println("['" + trimLeadingWhitespace(test3) + "']"); // ['無前導空白']
System.out.println("['" + trimLeadingWhitespace(test4) + "']"); // ['']
}
| 方法 | 行為 | 示例輸入 | 輸出 |
|---|---|---|---|
| trim() | 去除首尾空白 | " a b " | "a b" |
| stripLeading() (Java 11+) | 去除前導空白 (Unicode 感知) | " \n a" | "a" |
| replaceFirst("^\\s+", "") | 去除前導空白 (正則) | " \n a" | "a" |
| 手動遍歷 Character.isWhitespace | 去除前導空白 (高性能) | " \n a" | "a" |
// Java 11 引入,Unicode 感知,推薦使用
String result = str.stripLeading(); // 僅去除前導
String result2 = str.stripTrailing(); // 僅去除尾部
String result3 = str.strip(); // 去除首尾 (比 trim() 更完善)
stripLeading()replaceFirst("^\\s+", "") 可讀性好StringUtils.stripStart() 最穩健