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

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

当前回答

如果您正在使用Spring Boot,那么下面的代码将完成工作

StringUtils.hasLength(str)

其他回答

测试等于一个空字符串和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

使用org.apache.commons.lang.StringUtils

我喜欢用Apache common -lang来做这些事情,尤其是StringUtils实用程序类:

import org.apache.commons.lang.StringUtils;

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

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

这对我来说很管用:

import com.google.common.base.Strings;

if (!Strings.isNullOrEmpty(myString)) {
       return myString;
}

如果给定字符串为null或为空字符串,则返回true。 考虑用nullToEmpty规范字符串引用。如果你 做,你可以使用String.isEmpty()而不是这个方法,你不会吗 需要特殊的零安全形式的方法,如String.toUpperCase 要么。或者,如果你想“从另一个方向”正常化, 将空字符串转换为null,可以使用emptyToNull。

考虑下面的例子,我在main方法中添加了4个测试用例。当您遵循上面的注释片段时,将通过三个测试用例。

public class EmptyNullBlankWithNull {
    public static boolean nullEmptyBlankWithNull(String passedStr) {
        if (passedStr != null && !passedStr.trim().isEmpty() && !passedStr.trim().equals("null")) {
            // TODO when string is null , Empty, Blank
            return true;
        }else{
            // TODO when string is null , Empty, Blank
            return false;
        }
    }

    public static void main(String[] args) {
        String stringNull = null; // test case 1
        String stringEmpty = ""; // test case 2
        String stringWhiteSpace = "  "; // test case 3
        String stringWhiteSpaceWithNull = " null"; // test case 4
        System.out.println("TestCase result:------ "+nullEmptyBlankWithNull(stringWhiteSpaceWithNull));
        
    }
}

但是测试用例4将返回true(它在null之前有空格),这是错误的:

String stringWhiteSpaceWithNull = " null"; // test case 4

我们必须添加以下条件才能使其正常工作:

!passedStr.trim().equals("null")

简单地说,忽略空白:

if (str == null || str.trim().length() == 0) {
    // str is empty
} else {
    // str is not empty
}