isEmpty 和 isBlank 的区别

一般使用Apache commons-lang3 工具包;

commons-lang3 是专业的工具包,功能非常齐全、强大。

1、isEmpty

判断字符串是否为空字符串,只要有一个任意字符(包括空白字符)就不为空

isEmpty 的方法源码:

public static boolean isEmpty(CharSequence cs) {
    return cs == null || cs.length() == 0;
}
意味着,如果用户输入 "    " 等空白字符,这个方法就不通过了,结果就是不为空了。

2、isBlank

判断字符串是否为空字符串,全部空白字符也为空。

isBlank 的方法源码:

public static boolean isBlank(CharSequence cs) {
    int strLen = length(cs);
    if (strLen == 0) {
        return true;
    } else {
        for(int i = 0; i < strLen; ++i) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }

        return true;
    }
}

只要有一个字符不为空白字符就返回 false,也就是说,如果全部都为空白字符就返回 true,也就是全部空白字符也为空。
 
posted @ 2021-08-03 16:41  KLAPT  阅读(155)  评论(0编辑  收藏  举报