本文討論的 StringUtils 屬於
package org.apache.commons.lang;
字符串判空檢查
要了解字符串判空方法的區別首先要理解對象爲空字符串"" 和 null 的區別
“” 和 null 的區別
- null 是沒有地址的,可以理解爲空指針。當對象在構造器初始化時,如果沒有被顯示的賦於初值,那麼會默認賦值爲 null。
- “” 空字符串是一個 String 對象是有地址的,只是內容是空。
關於構造器初始化,在沒有顯示賦予初值的情況下。默認將數值型賦爲 0 , 布爾型是 false,對象引用則是 null。
String 並不是基本數據類型,而是對象所以會被默認的賦予 null。
isEmpty() 和 isBlank() 區別在於 isBlank() 可以多了對於空格的判斷,可以根據方法名區別使用 isEmpty() 判斷字符串是否爲空,而 isBlank() 則是判斷字符串是否是空格,空或null
isEmpty(String str)
isEmpty(), isNotEmpty() 判段字符串是否爲空或者null,空格返回false
/**
* <p>Checks if a String is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the String.
* That functionality is available in isBlank().</p>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is empty or null
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
isBlank(String str)
isEmpty(), isNotEmpty() 判段字符串是否爲空或者null,空格返回true
/**
* <p>Checks if a String is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}