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

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

当前回答

根据输入返回true或false

Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);

其他回答

那么isEmpty()呢?

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

请确保按此顺序使用&&的部分,因为如果&&的第一部分失败,java将不会继续计算第二部分,从而确保如果str为空,则不会从str. isempty()获得空指针异常。

注意,它只在Java SE 1.6以后可用。你必须在以前的版本上检查str.length() == 0。


也可以忽略空白:

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

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

封装在一个方便的函数中:

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

就变成:

if( !empty( str ) )

使用Apache StringUtils的isNotBlank方法

StringUtils.isNotBlank(str)

只有当str不为空时,它才会返回true。

如果你需要验证你的方法参数,你可以使用以下简单的方法

public class StringUtils {

    static boolean anyEmptyString(String ... strings) {
        return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
    }

}

例子:

public String concatenate(String firstName, String lastName) {
    if(StringUtils.anyBlankString(firstName, lastName)) {
        throw new IllegalArgumentException("Empty field found");
    }
    return firstName + " " + lastName;
}

根据输入返回true或false

Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);

测试等于一个空字符串和null在相同的条件:

if(!"".equals(str) && str != null) {
    // do stuff.
}

如果str为空则不抛出NullPointerException,因为Object.equals()如果arg为空则返回false。

另一个构造str.equals("")会抛出可怕的NullPointerException。有些人可能认为在调用equals()时使用String字面值作为对象是一种糟糕的形式,但它确实完成了这项工作。

还有这个答案:https://stackoverflow.com/a/531825/1532705