StringUtils的isEmpty和isBlank区别

导语

org.apache.commons.lang3 提供了String常用的操作,在日常的开发中,用到的非常多,常用的有isEmpty(String str)、isBlank(String str); 判断字符串是否为空、null、""等。但是这两个方法的使用是有一定的区别的,本片文章就专门分析一下这两个方法的不同。

maven依赖

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

StringUtils.isEmpty()方法

StringUtils.isEmpty(str) 判断字符串内容是否为空,为空标准是str==null || str.length()==0,包括null、""。

看下面的例子做具体的分析:

System.out.println(StringUtils.isEmpty(null));   结果 true
    
System.out.println(StringUtils.isEmpty(""));     结果true

System.out.println(StringUtils.isEmpty("  "));   结果false

System.out.println(StringUtils.isEmpty("aaa"));  结果false 

StringUtils.isNotEmpty(str) 等价于!str.isEmpty(str) 表示非空。

StringUtils.isBlank()方法

StringUtils.isBlank(str)判断字符串内容为空,内容为空包括 null、""、" "。

看下面的例子做具体的分析:

System.out.println(StringUtils.isBlank(null));  结果是true

System.out.println(StringUtils.isBlank(""));    结果是true

System.out.println(StringUtils.isBlank("  "));  结果是true

System.out.println(StringUtils.isBlank("aaa")); 结果是false

总结

通过上面的比较可以看出:

  1. isEmpty 没有忽略空格参数,是以是否为空和是否存在为判断依据。
  2. isBlank 是在 isEmpty 的基础上进行了为空(字符串都为空格、制表符、tab 的情况)的判断。(一般更为常用)
原创文章 59 获赞 287 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_45124488/article/details/105349534