首页 > 其他 > 详细

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

时间:2019-10-24 00:10:49      阅读:79      评论:0      收藏:0      [点我收藏+]

StringUtils.isBlank(str)和StringUtils.isEmpty(str)的区别还是看他们的实现有何不同

1.StringUtils.isEmpty(CharSequence cs)实现源码

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

从源码发现StringUtils.isEmpty(CharSequence cs)是判断了cs为null或cs.length()=0,但是我们要判断空白字符或者换行符等特殊的转义字符时,它的长度都是大于0的,所以用isEmpty判断是不行的

2.StringUtils.isBlank(CharSequence cs)实现源码

  •     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;
            }
        }

    从上可以发现,StringUtils.isBlank方法中比isEmpty多判断了空白字符即方法Character.isWhitespace    空白符有:空格、tab 键\n、换行符\t、回车符 \r 、换页符 \f

        

测试代码:

    public static void main(String[] args) {
        //isWhitespace() 方法用于判断指定字符是否为空白字符,空白符包含:空格、tab 键、换行符。
        System.out.println(Character.isWhitespace(‘c‘));
        System.out.println(Character.isWhitespace(‘ ‘));
        System.out.println(Character.isWhitespace(‘\n‘));
        System.out.println(Character.isWhitespace(‘\t‘));
        
        String str = "c";
        String str1 = "";
        String str2 = " ";
        String str3 = "\n";
        String str4 = "\t";
        System.out.println("is blank:" + StringUtils.isBlank(str3));
        System.out.println("is empty:" + StringUtils.isEmpty(str3));
    }
false
true
true
true
is blank:true
is empty:false
  • 3.结论:

  • 若要过滤掉空白符用StringUtils.isBlank方法,若仅仅是判断字符是否为null或长度是否为0则用StringUtils.isEmpty

 

 

 

 

 

 

      

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

原文:https://www.cnblogs.com/guanbin-529/p/11729678.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!