首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 去除字串前導空白字符(含換行、製表符)的實現方法

     編輯:程式設計綜合問答

在 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+", "");
}

方法三:Apache Commons Lang (生產環境推薦)


// 依賴: 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+ 標準庫新方法

// Java 11 引入,Unicode 感知,推薦使用
String result = str.stripLeading(); // 僅去除前導
String result2 = str.stripTrailing(); // 僅去除尾部
String result3 = str.strip(); // 去除首尾 (比 trim() 更完善)

性能建議

  • 高頻調用、大字串:使用手動遍歷或 stripLeading()
  • 一般業務邏輯:replaceFirst("^\\s+", "") 可讀性好
  • 專案已引入 Commons Lang:StringUtils.stripStart() 最穩健
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved