首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Apache Commons Lang StringUtils 工具類核心方法速查手冊

     編輯:Java 相關知識

StringUtils 核心價值

空指針安全、行為一致、高度優化**的字符串操作補完庫,消除無數 `if (str != null && str.length() > 0)` 樣板代碼。

核心方法分類速查

1. 數組/集合 ↔ 字符串轉換

方法說明示例
join(Object[])默認逗號分隔`join(new String[]{"a","b","c"}) → "a,b,c"`
join(Object[], String)指定分隔符`join(new String[]{"a","b","c"}, "@") → "a@b@c"`
join(Iterator) / join(Collection)支持迭代器/集合`join(Arrays.asList("a","b"), ";") → "a;b"`

2. 空值檢測 (null/empty 安全)

方法語義關鍵行為
isEmpty(CharSequence)null 或 ""`isEmpty(null)=true, isEmpty("")=true, isEmpty(" ")=false`
isNotEmpty(CharSequence)非 null 且非 ""`isNotEmpty(" ")=true` (空格視為非空)
isBlank(CharSequence)null、""、純空白`isBlank(" ")=true, isBlank("\t\n")=true`
isNotBlank(CharSequence)非 null、非 ""、非純空白`isNotBlank(" ")=false, isNotBlank("a")=true`
isAnyEmpty(CharSequence...)任一為 empty批量檢查參數
isNoneEmpty(CharSequence...)全非 empty批量檢查參數
isAnyBlank(CharSequence...)任一為 blank批量檢查參數
isNoneBlank(CharSequence...)全非 blank批量檢查參數

3. 修剪空白字符 (控制字符 ≤ 32)

方法行為返回值差異
trim(String)標準 `String.trim()`,null 返回 null`trim(null)=null, trim(" a ")=a`
trimToNull(String)trim 後為空則返回 null`trimToNull("")=null, trimToNull(" ")=null, trimToNull("a")=a`
trimToEmpty(String)trim 後為空則返回 ""`trimToEmpty(null)="", trimToEmpty(" " "")="", trimToEmpty("a")=a`
strip(String)同 trim,但處理 Unicode 空白Java 11+ `String.strip()` 行為
stripStart/End(String)單側修剪保留另一側空白

4. 大小寫轉換 (null 安全)

  • `capitalize(str)` — 首字母大寫
  • `uncapitalize(str)` — 首字母小寫
  • `swapCase(str)` — 大小寫互換
  • `upperCase/lowerCase(str)` — 全轉 (Locale 無關)

5. 子字符串查找/替換/截取 (null 安全)

場景方法說明
包含判斷`contains(str, search)` / `containsIgnoreCase` / `containsAny(str, chars)`返回 boolean
索引查找`indexOf/lastIndexOf(str, search)` / `indexOfAny/lastIndexOfAny`返回 int,-1 表示不存在
截取`substring(str, start)` / `substring(str, start, end)` / `substringBetween(str, open, close)` / `substringsBetween`負索引從末尾計算,越界安全
替換`replace(str, search, replacement)` / `replaceOnce` / `replacePattern/replaceAll` (正則)null 安全,空字符串處理合理
移除`remove(str, remove)` / `removeStart/End/IgnoreCase` / `removePattern`刪除指定子串/前綴/後綴/正則匹配

6. 分割與連接

  • `split(str, separatorChars)` — 字符集分割,保留空欄
  • `splitByWholeSeparator(str, separator)` — 完整字符串分隔符
  • `splitPreserveAllTokens` — 保留所有空 Token
  • `join` 見第 1 類

7. 填充與重複

  • `leftPad/rightPad/center(str, size)` / `leftPad/rightPad/center(str, size, padChar)`
  • `repeat(str, repeat)` — 字符串重複 N 次

8. 反轉與比較

  • `reverse(str)` — 字符序列反轉
  • `reverseDelimited(str, separator)` — 按分隔符分割後反轉順序
  • `compare(str1, str2)` / `compareIgnoreCase` — null 安全比較 (null < 非 null)

9. 字符集/編碼 (舊版本)

  • `getBytes(str, charset)` / `newString(bytes, charset)` — 異常安全包裝

最佳實踐模式

// 參數驗證一行式
if (StringUtils.isAnyBlank(param1, param2, param3)) {
    throw new IllegalArgumentException("參數不能為空");
}

// 安全截取
String domain = StringUtils.substringBetween(email, "@", "."); // null 安全

// 模板渲染
String sql = StringUtils.replace(template, "{table}", tableName);

// 日志輸出防 NPE
log.info("User: " + StringUtils.defaultString(user.getName(), "匿名"));

版本選擇建議

  • Commons Lang 3.x (org.apache.commons.lang3):Java 5+、模塊化、`StringUtils` 移至 `org.apache.commons.lang3.StringUtils`,**新項目首選**
  • Commons Lang 2.x (org.apache.commons.lang):舊項目維護,注意包名差異

總結

`StringUtils` 以 **null 安全** 為核心設計哲學,將字符串操作從「防衛性編程」解放為「意圖導向編程」。掌握 **isBlank/isNotBlank、trimToNull/trimToEmpty、join、substringBetween、replace、split** 等高頻方法,可消除 80% 以上的字符串處理樣板代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved