org.apache.commons.lang.StringUtils 类提供了 String 的常用操作,最为常用的判断是否为空的方法isEmpty(String str) 和 isBlank(String str)。
以下是两个方法源码:
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;
}
}
StringUtils.isBlank(String str)判断某字符串是否为空或长度为 0 或由空白符 (whitespace) 构成
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
StringUtils.isEmpty(String str)判断某字符串是否为空,为空的标准是 str==null 或str.length()==0
建议:StringUtils.isBlank(String str) 来执行判空操作,判断的条件更多更具体,特别是进行参数校验时,推荐使用。
测试代码:
String s=" ";
System.out.println(StringUtils.isBlank(s));//true
System.out.println(StringUtils.isEmpty(s));//false