StringUtils.isEmpty()和StringUtils.isBlank()区别

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()方法更加常用。
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java-请多指教

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值