StringUtils中的字符串判空

StringUtils中的字符串判空

判空操作在我们工作用过是比较常用的一个操作,commons-lang3这个包为我们提供了两个判空的方法,分别是StringUtils.isEmpty(CharSequence cs)和StringUtils.isBlank(CharSequence cs),那有什么区别呢,今天就记录一下
1.maven地址

		<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>

2.isEmpty()源码和用法

  public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

通过源码我们可以得知isEmpty() 方法校验的是字符串的长度和字符串是否是null,故空格将会通过校验。

public class StringOne {
    public static void main(String[] args) {
        System.out.println(StringUtils.isEmpty(null));//true
        System.out.println(StringUtils.isEmpty(""));//true
        System.out.println(StringUtils.isEmpty(" "));//false
        System.out.println(StringUtils.isEmpty("hzm"));//false
    }
}

3.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;
        }
    }

这个方法除了判断字符串是否为null和长度是否为零,还判断了是否为空格,如果是空格也返回true。

public class StringOne {
    public static void main(String[] args) {
        System.out.println(StringUtils.isBlank(null));//true
        System.out.println(StringUtils.isBlank(""));//true
        System.out.println(StringUtils.isBlank(" "));//true
        System.out.println(StringUtils.isBlank("\n"));//true
        System.out.println(StringUtils.isBlank("hzm"));//false
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值