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

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

当前回答

如果您正在使用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

其他回答

如果您正在使用Spring Boot,那么下面的代码将完成工作

StringUtils.hasLength(str)

使用org.apache.commons.lang.StringUtils

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

import org.apache.commons.lang.StringUtils;

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

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

我已经制作了自己的实用函数来一次检查几个字符串,而不是有一个充满if(str != null && !str的if语句。= null && !str2.isEmpty)。这是函数:

public class StringUtils{

    public static boolean areSet(String... strings)
    {
        for(String s : strings)
            if(s == null || s.isEmpty)
                return false;

        return true;
    }   

}

所以我可以简单地写:

if(!StringUtils.areSet(firstName,lastName,address)
{
    //do something
}

简单地说,忽略空白:

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

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

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

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

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

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


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