前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >StringUtils里面的 isEmpty方法和isBlank方法的区别[通俗易懂]

StringUtils里面的 isEmpty方法和isBlank方法的区别[通俗易懂]

作者头像
全栈程序员站长
发布2022-06-30 19:14:10
4450
发布2022-06-30 19:14:10
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

写在前面: 我是「扬帆向海」,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活

文章目录

1、isEmpty() 方法

源码

在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
public static boolean isEmpty(String str) { 
   
		// 判断字符串是否为空或长度为0
        return str == null || str.length() == 0;

isEmpty 是判断某个字符串是否为空,判断的标准是 str == null || str.length() == 0

测试:

代码语言:javascript
复制
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

    }
}
2、isBlank()方法

源码:

在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
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;
        }
    }

isBlank 是判断字符串是否为空或长度为0 或者是由空白符构成

测试

代码语言:javascript
复制
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
    
    }
}
3、总结
  • isEmpty()方法没有忽略空格,是以是否为空和是否存在为判断依据;
  • isBlank()方法增加了字符串为空格、制表符的判断。即isBlank()的判断范围更大,它在isEmpty()方法的基础上,包括了空字符的判断。在实际开发中,isBlank()方法更加常用。

由于水平有限,本博客难免有不足,恳请各位大佬不吝赐教!

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/132167.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
    • 1、isEmpty() 方法
      • 2、isBlank()方法
        • 3、总结
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档