StringUtils之isBlank分析

打开org.apache.commons.lang包下面的StringUtils.class

 /**
     * <p>Checks if a String is whitespace, empty ("") or null.</p>
     *
     * <pre>
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * </pre>
     *
     * @param str  the String to check, may be null
     * @return <code>true</code> if the String is null, empty or whitespace
     * @since 2.0
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

传入一个String类型的参数,返回一个boolean类型

首先判断是否等于null或者长度为0,满足一个就返回true代表空白字符串

如果都不是接着验证

for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }

str.charAt是根据索引,返回字符,这个索引是从0开始的


    String str = "Hello World";
                   
    System.out.println(str.charAt(0));
          
    System.out.println(str.charAt(5));
          
    System.out.println(str.charAt(8));
执行后输出

H


r


所以这段代码是判断string字符的每个位置是否为空白格,如果是空白格的返回true,不是的返回false,然后做个判断==false,正好相反,只要有一个不是空白格,就返回错误

 if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }

 

 public static boolean isWhitespace(int codePoint) {
        return CharacterData.of(codePoint).isWhitespace(codePoint);
    }


总结:StringUtils.isBlank时先判断

1.是否等于null或者长度为0,

2.如果都不行就考虑传进来的参数是否都是空白格,就是这种   "        ",里面都是空格,

如果都不满足,那这个参数不是blank的

顺便看下StringUtils.isNotBlank的源码,只是调用StringUtils.isBlank加个

   public static boolean isNotBlank(String str) {
        return !StringUtils.isBlank(str);
    }



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值