org.apache.commons.lang.StringUtils类提供了String的常用操作,最为常用的判空有如下两种isEmpty(String str)和isBlank(String str)。
那么针对这两种为空的判断有什么区别呢?
1、StringUtils.isEmpty(String str) 判断某字符串是否为空,为空的标准是 str==null 或 str.length()==0,具体实现代码如图:
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
System.out.println(StringUtils.isEmpty(null)); //true
System.out.println(StringUtils.isEmpty("")); //true
System.out.println(StringUtils.isEmpty(" ")); //false
System.out.println(StringUtils.isEmpty("dd")); //false
2、StringUtils.isBlank(String str) 判断某字符串是否为空或长度为0或由空白符(whitespace) 构成,具体实现代码如图:
public static boolean isBlank(String str) {
int strLen;
if (str != null && (strLen = str.length()) != 0) {
for(int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
System.out.println(StringUtils.isBlank(null)); //true
System.out.println(StringUtils.isBlank("")); //true
System.out.println(StringUtils.isBlank(" ")); //true
System.out.println(StringUtils.isBlank("dd")); //false
所以,StringUtils.isBlank 比 StringUtils.isEmpty 多了空白符的判断。