一. 概述
- StringUtils類是操作String類型數據的常用工具類。
- 所屬包:
org.apache.commons.lang.StringUtils
或org.apache.commons.lang3.StringUtils
(建議使用後者)
- maven依賴(
org.apache.commons.lang3.StringUtils
)<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
二. 常用方法
- 這裏介紹的方法都屬於
org.apache.commons.lang3.StringUtils
類。
1. isEmpty(final CharSequence cs)
- 概述:檢查字符串str是否爲null或“”。
- 源碼
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
- 舉例
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
2. isNotEmpty(final CharSequence cs)
- 概述:檢查字符串str是否非null,非“”。
- 源碼
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
- 舉例
StringUtils.isNotEmpty(null) = false
StringUtils.isNotEmpty("") = false
StringUtils.isNotEmpty(" ") = true
StringUtils.isNotEmpty("bob") = true
StringUtils.isNotEmpty(" bob ") = true
3. isBlank(final CharSequence cs)
- 概述:檢查字符串str是否爲null,"",或空白(" ")。
- 舉例
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
4. isNotBlank(final CharSequence cs)
- 概述:檢查字符串str是否非null,非"",非空白(" ")。
- 舉例
StringUtils.isNotBlank(null) = false
StringUtils.isNotBlank("") = false
StringUtils.isNotBlank(" ") = false
StringUtils.isNotBlank("bob") = true
StringUtils.isNotBlank(" bob ") = true
5. equals(final CharSequence cs1, final CharSequence cs2)
- 概述
- 比較兩個字符串。如果相同,則返回true。
- 如果兩個字符串都爲null,返回true。此方法與String類的equals方法相比,可以判斷兩個null值。
- 舉例
StringUtils.equals(null, null) = true
StringUtils.equals(null, "abc") = false
StringUtils.equals("abc", null) = false
StringUtils.equals("abc", "abc") = true
StringUtils.equals("abc", "ABC") = false
6. join(CharSequence delimiter, CharSequence... elements)
- 概述:用指定分隔符連接數組各個元素。
- 舉例
String message = String.join("-", "Java", "is", "cool");
參考資料
Java工具類StringUtils常用方法整理