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

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

当前回答

如果你不想包含整个库;只包括你想要的代码。你得自己维护;但这是一个很简单的函数。这里是从commons.apache.org复制的

    /**
 * <p>Checks if a String is whitespace, empty ("") or null.</p>
 *
 * <pre>
 * StringUtils.isBlank(null)      = true
 * StringUtils.isBlank("")        = true
 * StringUtils.isBlank(" ")       = true
 * StringUtils.isBlank("bob")     = false
 * StringUtils.isBlank("  bob  ") = false
 * </pre>
 *
 * @param str  the String to check, may be null
 * @return <code>true</code> if the String is null, empty or whitespace
 * @since 2.0
 */
public static boolean isBlank(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if ((Character.isWhitespace(str.charAt(i)) == false)) {
            return false;
        }
    }
    return true;
}

其他回答

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

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

这对我来说很管用:

import com.google.common.base.Strings;

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

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

如何:

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

我知道的几乎每个库都定义了一个名为StringUtils、StringUtil或StringHelper的实用程序类,它们通常包含你正在寻找的方法。

我个人最喜欢的是Apache Commons / Lang,在StringUtils类中,你可以同时得到

StringUtils.isEmpty(字符串)和 StringUtils.isBlank (String)方法

(第一个检查字符串是空的还是空的,第二个检查它是空的,空的还是空白的)

在Spring、Wicket和许多其他库中也有类似的实用程序类。如果不使用外部库,您可能希望在自己的项目中引入一个StringUtils类。


更新:许多年过去了,现在我建议使用Guava的Strings.isNullOrEmpty(string)方法。

简单地说,忽略空白:

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