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

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;
}

其他回答

使用Apache StringUtils的isNotBlank方法

StringUtils.isNotBlank(str)

只有当str不为空时,它才会返回true。

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

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

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

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

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

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

如果您正在使用Java 8并希望采用更函数式编程的方法,您可以定义一个函数来管理控件,然后您可以重用它并在需要时应用()。

在实践中,您可以将函数定义为

Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)

然后,你可以通过简单地调用apply()方法来使用它:

String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true

如果您愿意,您可以定义一个函数来检查String是否为空,然后用!对其求反。

在这种情况下,函数看起来像:

Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)

然后,你可以通过简单地调用apply()方法来使用它:

String emptyString = "";
!isEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true

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

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