StringUtils工具包中的isBlank函数

StringUtils工具包中的isBlank函数

isBlank( )函数位于 org.apache.commons.lang.StringUtils工具包中,该函数的功能是判断传入的变量是否为空(通常为String类型)

在判断一个String变量是否为空时,通常分为以下三种情况:
(1)变量是否为null
(2)变量是否为“”
(3)变量是否为空字符串“       ”

isBlank( )函数能够一次性判断以上三种情况,返回值都是为true。

isBlank( )函数源码如下:
public static boolean isBlank(String str) {
    int strLen;
    if(str 1= null && (strLen = str.length()) 1= 0) {
        for(int i=0; i<strLen; ++i) {
            if(!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }

        return true;
    } else {
        return true;
    }
}

测试
import org.apache.commons.lang.StringUtils;

public class isBlankTest {
    public static void main(String[] args) {
        System.out.println(StringUtils.isBlank(null));
        System.out.println(StringUtils.isBlank(""));
        System.out.println(StringUtils.isBlank(" "));
        System.out.println(StringUtils.isBlank("abc"));
        System.out.println(StringUtils.isBlank(" abc "));
    }
}

结果为:
true
true
true
false
false

猜你喜欢

转载自blog.csdn.net/YF_Li123/article/details/79963358
今日推荐