StringUtils里面的 isEmpty方法和isBlank方法的区别(亲测)

写在前面: 我是「扬帆向海」,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。

这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。

用知识改变命运,让我们的家人过上更好的生活。

文章目录
1、isEmpty() 方法
2、isBlank()方法
3、总结
1、isEmpty() 方法
源码:


public static boolean isEmpty(String str) {
        // 判断字符串是否为空或长度为0
        return str == null || str.length() == 0;
    
1
2
3
4
isEmpty 是判断某个字符串是否为空,判断的标准是 str == null || str.length() == 0

测试:

public class TestStringUtils {

    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("扬帆向海")); // false
        System.out.println(StringUtils.isEmpty(" 扬帆向海 ")); // false

    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
2、isBlank()方法
源码:


public static boolean isBlank(String str) {
        int strLen;
        // 判断字符串是否为空或长度为是否为0
        if (str != null && (strLen = str.length()) != 0) {
            // 如果字符串不为空,且长度不为0,进行循环遍历
            for(int i = 0; i < strLen; ++i) {
                // 如果字符串指定位置的值不为空白字符,返回false;否则返回true
                if (!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
isBlank 是判断字符串是否为空或长度为0 或者是由空白符构成

测试:

public class TestStringUtils {

    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("扬帆向海")); // false
        System.out.println(StringUtils.isBlank(" 扬帆向海 ")); // false
    
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
3、总结
isEmpty()方法没有忽略空格,是以是否为空和是否存在为判断依据;

isBlank()方法增加了字符串为空格、制表符的判断。即isBlank()的判断范围更大,它在isEmpty()方法的基础上,包括了空字符的判断。在实际开发中,isBlank()方法更加常用。
————————————————
版权声明:本文为CSDN博主「扬帆向海 」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43570367/article/details/104392515

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值