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

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

当前回答

正如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 **/
}

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

其他回答

那么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 ) )

我遇到过一种情况,我必须检查“null”(作为字符串)必须被视为空。空格和实际null必须返回true。 我最终确定了下面的函数…

public boolean isEmpty(String testString) {
  return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}

在这里添加Android:

import android.text.TextUtils;

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

如果有人使用springboot,那么下面的选项可能会有帮助,

import static org.springframework.util.StringUtils.hasLength;
if (hasLength(str)) {
  // do stuff
}

str != null && str.length() != 0

另外

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

or

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

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

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