字符串判空、判等

一、字符串判空

字符串为null 或' '时返回true。

1.1 常用方法

  • str == null || str.length() < 1 String提供的

  • str == null || str.isEmpty() String提供的

  • StringUtils.isEmpty(str) StringUtils提供的(✅推荐)

1.2 isEmpty

String 和 StringUtils都提供了isEmpty方法,但是

  • String提供的isEmpty:当对象为null时,会报空指针异常的错误
  • StringUtils提供的isEmpty(✅推荐):null、空字符串""是都返回true,即先判断==null,再判断是否为空,不会发生空指针异常错误 (StringUtils是由jdk提供的,相当于增强工具包)
// String
    public boolean isEmpty() {
        return value.length == 0;
    }
// StringUtils(以org.apache.commons.lang为例)
   public static boolean isEmpty(String str) {
         return str == null || str.length() == 0;
    }    

1.3 isBlank

isBlank 是在 isEmpty 的基础上增加了是否为whiteSpace(空白字符:空格、制表符、tab )的判断

复制代码
    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;
    }
复制代码

举例说明isBlank和isEmpty的区别

StringUtils.isEmpty("yyy") = false
StringUtils.isEmpty("") = true
StringUtils.isEmpty("   ") = false
 
StringUtils.isBlank("yyy") = false
StringUtils.isBlank("") = true
StringUtils.isBlank("   ") = true

二、字符串判等

  • 使用String包, str1.equals(str2):本方法需要注意str1非null,否则NPE
  • 使用Objects.equals(str1, str2) ✅推荐

说明:

1、== 比较的内存地址。 字符串是对象类型,所以不能用简单的“==”判断

2、equals()比较的是对象的内容(区分字母的大小写格式)是否相等

 

posted @   zhegeMaw  阅读(60)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示