检查字符串是否不为空且不为空

检查字符串是否不为空且不为空

问题描述:

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

How can I check whether a string is not null and not empty?

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 为空,您不会从 str.isEmpty() 得到空指针异常.

Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.

请注意,它仅从 Java SE 1.6 开始可用.您必须检查以前版本的 str.length() == 0.

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.

也要忽略空格:

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

(自 Java 11 str.trim().isEmpty() 可以简化为 str.isBlank(),这也将测试其他 Unicode 空格)

(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)

包裹在一个方便的函数中:

Wrapped in a handy function:

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

变成:

if( !empty( str ) )