检查一个字符串是否既不为null也不为空。

561

如何检查一个字符串既不是 null 也不是空的?

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

8
最好使用 PreparedStatement 等代替通过字符串连接原语构建 SQL 查询。这样可以避免各种注入漏洞,而且更易读等。 - polygenelubricants
2
你可以创建一个类来检查空值或空对象。这将有助于提高可重用性。http://stackoverflow.com/a/16833309/1490962 - Bhushankumar Lilapara
此条件可以用java.util.function.Predicate表达,如下所示:Predicate.<String>isEqual(null).or(String::isEmpty).negate(),具体解释请参考这里 - Alexander Ivanchenko
35个回答

0
我遇到了这样一种情况,必须检查"null"(作为字符串)是否应被视为空。同时,空格和实际的null也必须返回true。我最终选择了以下函数...
public boolean isEmpty(String testString) {
  return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}

0
如果您需要验证方法参数,可以使用以下简单方法。
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;
}

0

为了检查对象中是否所有的字符串属性都为空(而不是使用Java反射API方法在所有字段名后面使用!=null)

private String name1;
private String name2;
private String name3;

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this) != null) {
                return false;
            }
        } catch (Exception e) {
            System.out.println("Exception occurred in processing");
        }
    }
    return true;
}

如果所有字符串字段的值都为空,则此方法将返回true;如果任何一个值存在于字符串属性中,则返回false。


-1

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

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

简而言之,
str.length()>0 && !str.equalsIgnoreCase("null")

-1
import android.text.TextUtils;

if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
    ...
}

1
添加一些解释比仅有代码更好。例如,为什么你要导入一个库? - Edgar H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接