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

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

当前回答

你应该使用org.apache.commons.lang3.StringUtils.isNotBlank()或org.apache.commons.lang3.StringUtils.isNotEmpty。这两者之间的决定是基于您实际想要检查的内容。

isNotBlank()检查输入参数是否为:

非空, 不是空字符串("") 不是空白字符序列(" ")

isNotEmpty()只检查输入参数是否为

非空 不是空字符串("")

其他回答

在这里添加Android:

import android.text.TextUtils;

if (!TextUtils.isEmpty(str)) {
...
}

如果你使用Spring框架,那么你可以使用method:

org.springframework.util.StringUtils.isEmpty(@Nullable Object str);

该方法接受任何Object作为参数,将其与null和空String进行比较。因此,对于非空的非string对象,此方法永远不会返回true。

处理字符串中的null更好的方法是,

str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()

简而言之,

str.length()>0 && !str.equalsIgnoreCase("null")

考虑下面的例子,我在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")

你应该使用org.apache.commons.lang3.StringUtils.isNotBlank()或org.apache.commons.lang3.StringUtils.isNotEmpty。这两者之间的决定是基于您实际想要检查的内容。

isNotBlank()检查输入参数是否为:

非空, 不是空字符串("") 不是空白字符序列(" ")

isNotEmpty()只检查输入参数是否为

非空 不是空字符串("")