StringUtils.isBlank的用法与区别是什么

发布时间:2021-12-10 10:03:52 作者:柒染
来源:亿速云 阅读:249

StringUtils.isBlank的用法与区别是什么,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

在我们日常开发中,判空应该是最常用的一个操作了。因此项目中总是少不了依赖commons-lang3包。这个包为我们提供了两个判空的方法,分别是StringUtils.isEmpty(CharSequence cs)和StringUtils.isBlank(CharSequence cs)。我们分别来看看这两个方法有什么区别。

一、StringUtils.isEmpty

isEmpty的源码如下:

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

这个方法判断的是字符串是否为null或者其长度是否为零。

「测试效果」

public class BlankAndEmpty {
   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("\t")); //false        System.out.println(StringUtils.isEmpty("Java旅途")); //false    }}
 

二、StringUtils.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;    }}
 

length(cs)的方法如下

public static int length(CharSequence cs) {    return cs == null ? 0 : cs.length();}
 

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

「测试效果」

public class BlankAndEmpty {
   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("\t")); //true        System.out.println(StringUtils.isBlank("Java旅途")); //false    }}

三、总结

 

四、扩展

  1. 在实际开发中,除了isBlank判空的几种情况之外,其实“null”字符串我们也会当作空字符串处理。

  2. 我们需要判断几个字段同时不能为空,如果还用isBlank就显得有点累赘了。我们可以使用String的可变参数提供如下工具类。

public class StringTool {
   public static boolean isNullStr(String... args) {        boolean falg = false;        for (String arg : args) {            if (StringUtils.isBlank(arg) || arg.equals("null")) {                falg = true;                return falg;            }        }        return falg;    }}

这个工具类的优点很明显,一方面判断了字符串“null”,另一方面对参数个数无限制,只要有一个参数是空则返回true。

看完上述内容,你们掌握StringUtils.isBlank的用法与区别是什么的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. php this self 用法与区别
  2. jQuery中的$(window)与$(document)的用法区别

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:php文件如何按修改时间排序

下一篇:Redis中如何实现消息队列和延时消息队列

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》