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

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.lang.StringUtils

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

import org.apache.commons.lang.StringUtils;

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

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

其他回答

在这里添加Android:

import android.text.TextUtils;

if (!TextUtils.isEmpty(str)) {
...
}
str != null && str.length() != 0

另外

str != null && !str.equals("")

or

str != null && !"".equals(str)

注意:第二次检查(第一个和第二个替代)假设str不为空。这只是因为第一次检查是这样做的(如果第一次检查为假,Java不会进行第二次检查)!

重要:不要用==表示字符串相等。==检查指针是否相等,而不是值。两个字符串可以在不同的内存地址(两个实例),但具有相同的值!

简单地说,忽略空白:

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

正如seanizer上面所说,Apache StringUtils在这方面非常出色,如果你要包括guava,你应该做以下工作;

public List<Employee> findEmployees(String str, int dep) {
 Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
 /** code here **/
}

我还建议您通过名称而不是索引来引用结果集中的列,这将使您的代码更容易维护。

根据输入返回true或false

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