简单介绍
我们平时在项目中,常会使用org.apache.commons.lang3.StringUtils来进行 字符串 的判断操作,在StringUtils类中,有这么两个方法isEmpty()和isBlank()都可以作为字符串的判断处理,但两者有什么区别?
源码分析
public static boolean isEmpty(final CharSequence cs ) {
return cs == null || cs.length() == 0;
}
可以看出isEmpt(..)方法是采用判断字符的长度来进行空判断,长度为0,则返回空
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
这一段代码里,在第一个if里同样使用了判断长度的方式。
不同的是,在判断长度大于0的情况后,调用了Character.isWhitespace(..)方法,这个方法的作用是判断是否包含空格,例如”\n”,”\t”这种换行等 占位符
模拟测试
@Test
public void testStringUtils() {
String str = ” “; 一个空格的字符串
System.out.println(StringUtils.isBlank(str)); true
System.out.println(StringUtils.isEmpty(str)); false
str = “”; 空串
System.out.println(StringUtils.isBlank(str)); true
System.out.println(StringUtils.isEmpty(str)); true
str = null;
System.out.println(StringUtils.isBlank(str)); true
System.out.println(StringUtils.isEmpty(str)); true
str = “\t\r\n”; 各种空格占位符
System.out.println(StringUtils.isBlank(str)); true
System.out.println(StringUtils.isEmpty(str)); false
}
总结
当需要判断指定字符串是否为空””与null时使用isEmpty()
当有特殊要求,例如空格也算为空,” “,\t\r\n这种默认视为空的可以使用isBlank()
在判断””与null时二者可以互相替换,若有空格isEmpty()是false的但是isBlank()就是true