StringUtils 的操作对象是 Java.lang.String 类型的对象,是 JDK 提供的 String 类型操作方法的补充,输入的 String参数 为 null 也不会抛出 NullPointerException异常 ,而是做了相应处理,例如,如果输入为 null 则返回也是 null 等,具体可以查看源代码,
在实际工作中,我们需要对字符串进行一些校验,比如:是否为 null,是否为空,是否去掉空格、换行符、制表符等。一般都是通过一些框架的工具类去做这些判断,比如:apache 的 commons jar 包,如下。
package org.apache.commons.lang3;
下面主要介绍isEmpty方法和isBlank方法。
一、isEmpty方法
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
以上是isEmpty方法源代码,由源码可知判断某字符串是否为空的标准是 str==null 或 str.length()==0
举几个例子:
public void test() {
System.out.println(StringUtils.isEmpty(""));//ture
System.out.println(StringUtils.isEmpty(" "));//false
System.out.println(StringUtils.isEmpty(" "));//false
System.out.println(StringUtils.isEmpty(null));//true
System.out.println(StringUtils.isEmpty("null"));//false
System.out.println(StringUtils.isEmpty(" empty "));//false
}
二、isBlank方法
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs != null && (strLen = cs.length()) != 0) {
for(int i = 0; i < strLen; ++i) {
//判断字符是否为空格、制表符、换行符
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
以上是isBlank方法的源代码,其中Character.isWhitespace() 方法用于判断指定字符是否为空白字符,空白符包含:空格、tab键、换行符。由源码可知其判断某字符串是否为空或长度为0或由空白符(whitespace) 构成。
举例:
public void test() {
System.out.println(StringUtils.isBlank(""));//ture
System.out.println(StringUtils.isBlank(" "));//true
System.out.println(StringUtils.isBlank(" "));//true
System.out.println(StringUtils.isBlank(null));//true
System.out.println(StringUtils.isBlank("null"));//false
System.out.println(StringUtils.isBlank(" blank "));//false
//制表符
System.out.println(StringUtils.isBlank("\t"));//true
//换行符
System.out.println(StringUtils.isBlank("\n"));//true
//换页符
System.out.println(StringUtils.isBlank("\f"));//true
//回车符
System.out.println(StringUtils.isBlank("\r"));//true
}
三、结论
1. isEmpty()方法没有忽略空格,是以是否为空和是否存在为判断依据;
2. isBlank()方法的判断范围更大,它是在isEmpty()方法的基础上增加了字符串为空格、制表符等判断。在实际开发中,isBlank()方法更加常用。