1.40 检查字符串是否不为空且不为空 | Java Debug 笔记

178 阅读1分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看 活动链接

Debug 笔记 <检查字符串是否不为空且不为空>

提问

如何检查字符串是否不为null也不为空?

public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty string */
    }
    /* ... */
}

回答一

isEmpty()呢?

if(str != null && !str.isEmpty())

确保&&按此顺序使用的部分,因为如果的第一部分&&失败,java将不会继续评估第二部分,从而确保您不会从str.isEmpty()ifstrnull的情况下得到null指针异常。

当心,它仅从Java SE 1.6起可用。您必须检查str.length() == 0以前的版本。

也要忽略空格:

if(str != null && !str.trim().isEmpty())

(因为str.trim().isEmpty()可以将Java 11简化为str.isBlank()也可以测试其他Unicode空白)

包裹在一个方便的功能中:

public static boolean empty( final String s ) {
  // Null-safe, short-circuit evaluation.
  return s == null || s.trim().isEmpty();
}

成为:

if( !empty( str ) )

回答二

使用org.apache.commons.lang.StringUtils

我喜欢将Apache commons-lang用于这类事情,尤其是StringUtils实用程序类:

import org.apache.commons.lang.StringUtils;

if (StringUtils.isNotBlank(str)) {
    ...
} 

if (StringUtils.isBlank(str)) {
    ...
} 

回答三

str != null && str.length() != 0 或者 str != null && !str.equals("") 或者 str != null && !"".equals(str)

注意:第二个检查(第一个和第二个选择)假定str不为null

没关系,因为第一次检查是这样做的(如果第一次检查为falseJava不会进行第二次检查)!

重要说明:请勿将==用于字符串相等。==检查指针是否相等,而不是值。

两个字符串可以位于不同的内存地址(两个实例)中,但具有相同的值!

文章翻译自Stack Overflow :stackoverflow.com/questions/3…