org.apache.commons.lang3.StringUtils 是 Java 開發中最常用的字串處理工具類,提供 130 多個 static 方法,且皆為 null-safe(傳入 null 不拋出 NPE)。本文精選高頻方法分類詳解,附帶實測輸出對照表。
| 分類 | 代表方法 | 用途 |
|---|---|---|
| 空值檢查 | isEmpty, isNotEmpty, isBlank, isNotBlank | 判斷字串是否為 null、空字串、或僅含空白字元 |
| 去除空白 | trim, trimToNull, trimToEmpty, strip, stripToNull, stripToEmpty | 移除首尾空白字元(strip 含 Unicode 空白) |
| 比較 | equals, equalsIgnoreCase | null-safe 字串比較 |
| 查找索引 | indexOf, lastIndexOf, ordinalIndexOf | 尋找字元/子字串位置,支援指定起始位置與第 N 次出現 |
| 子字串 | substring, substringBefore, substringAfter, substringBetween | 擷取子字串 |
| 分割/連接 | split, join | 字串分割與陣列/集合連接 |
| 替換/移除 | replace, replaceOnce, remove, removeStart, removeEnd | 字串替換與移除 |
| 大小寫轉換 | capitalize, uncapitalize, swapCase, lowerCase, upperCase | 字串大小寫轉換 |
| 填充/對齊 | leftPad, rightPad, center, repeat | 字串填充、置中、重複 |
// isEmpty:僅判斷 null 或 ""
StringUtils.isEmpty(null) // true
StringUtils.isEmpty("") // true
StringUtils.isEmpty(" ") // false(含空格不視為 empty)
StringUtils.isEmpty("\t\n") // false
// isBlank:判斷 null、""、或僅含空白字元(含 \t\n\r\f)
StringUtils.isBlank(null) // true
StringUtils.isBlank("") // true
StringUtils.isBlank(" ") // true
StringUtils.isBlank("\t\n") // true
StringUtils.isBlank("\b") // false(退位符非空白字元)
StringUtils.trim(null) // null
StringUtils.trim("") // ""
StringUtils.trim(" ") // ""
StringUtils.trim("\t\n") // ""
StringUtils.trim("\b") // ""(trim 視 \b 為控制字元而移除)
StringUtils.strip(null) // null
StringUtils.strip(" ") // ""
StringUtils.strip("\t\n") // ""
StringUtils.strip("\b") // "\b"(strip 僅移除 Character.isWhitespace 為 true 的字元,\b 不在內)
// trimToNull:trim 後若為空字串則回傳 null
StringUtils.trimToNull(" ") // null
StringUtils.trimToNull("abc") // "abc"
// trimToEmpty:trim 後若為 null 則回傳 ""
StringUtils.trimToEmpty(null) // ""
StringUtils.trimToEmpty(" ") // ""
StringUtils.equals(null, null) // true
StringUtils.equals("abc", "ABC") // false
StringUtils.equalsIgnoreCase("abc", "ABC") // true
StringUtils.indexOf("aabaabaa", "a", 0) // 0
StringUtils.indexOf("aabaabaa", "a", 1) // 1
StringUtils.ordinalIndexOf("aabaabaa", "a", 3) // 3(第 3 次出現位置)
StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) // 4
org.apache.commons:commons-lang3(注意 groupId 為 commons-lang3,非舊版 commons-lang)。str == null || str.isEmpty())可能比工具類略快,但可讀性與安全性通常優先。String.isBlank()、String.strip() 等原生方法已涵蓋部分功能,新專案可評估原生 API 是否足夠。StringUtils 是 Java 開發者的「瑞士刀」,熟練掌握其核心方法能大幅提升字串處理的效率與健壯性。建議將常用方法整理成團隊速查表,程式碼審查時優先檢查是否妥善使用 null-safe 方法。