检查字符串是否不为null和不为空

bkhjykvo  于 2021-07-03  发布在  Java
关注(0)|答案(30)|浏览(402)

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

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

lp0sw83n1#

在字符串中处理null的更好方法是,

str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()

总之,

str.length()>0 && !str.equalsIgnoreCase("null")
u5rb5r59

u5rb5r592#

简单地说,也可以忽略空白:

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

1cklez4t3#

完整性:如果您已经在使用spring框架,那么stringutils提供了

org.springframework.util.StringUtils.hasLength(String str)

如果字符串不为null且长度为,则返回:true
以及方法

org.springframework.util.StringUtils.hasText(String str)

返回:true如果字符串不为null,其长度大于0,并且不仅包含空格

6za6bjd0

6za6bjd04#

使用org.apache.commons.lang.stringutils

我喜欢使用apache commons lang来处理这类事情,尤其是stringutils实用程序类:

import org.apache.commons.lang.StringUtils;

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

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

xzabzqsa5#

如果你不想包括整个图书馆;只要包含你想要的代码。你得自己维护它;但这是一个非常直接的函数。这里是从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;
}
sf6xfgos

sf6xfgos6#

如果您使用的是Java8,并且希望有一种更具功能性的编程方法,那么可以定义 Function 管理控件,然后您可以重用它并 apply() 无论何时需要。
开始练习,你可以定义 Function 作为

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

如果您愿意,可以定义 Function 检查是否 String 是空的,然后用 ! .
在这种情况下 Function 看起来像:

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
iyfjxgzm

iyfjxgzm7#

如果需要验证方法参数,可以使用以下简单方法

public class StringUtils {

    static boolean anyEmptyString(String ... strings) {
        return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
    }

}

例子:

public String concatenate(String firstName, String lastName) {
    if(StringUtils.anyBlankString(firstName, lastName)) {
        throw new IllegalArgumentException("Empty field found");
    }
    return firstName + " " + lastName;
}
xqk2d5yq

xqk2d5yq8#

这对我很有用:

import com.google.common.base.Strings;

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

如果给定字符串为null或为空字符串,则返回true。
考虑使用nulltoempty规范化字符串引用。如果这样做,可以使用string.isempty()而不是此方法,并且也不需要像string.touppercase这样的特殊的空安全形式的方法。或者,如果希望“在另一个方向”进行规范化,将空字符串转换为null,则可以使用emptytonull。

x3naxklr

x3naxklr9#

有点晚了,但这里有一种功能性的检查方式:

Optional.ofNullable(str)
    .filter(s -> !(s.trim().isEmpty()))
    .ifPresent(result -> {
       // your query setup goes here
    });
omvjsjqw

omvjsjqw10#

java-11中有一个新方法: String#isBlank 如果字符串为空或仅包含空白代码点,则返回true,否则返回false。

jshell> "".isBlank()
$7 ==> true

jshell> " ".isBlank()
$8 ==> true

jshell> " ! ".isBlank()
$9 ==> false

这可以与 Optional 检查字符串是否为null或空

boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);

字符串#为空

olmpazwi

olmpazwi11#

简单解决方案:

private boolean stringNotEmptyOrNull(String st) {
    return st != null && !st.isEmpty();
}
jtoj6r0c

jtoj6r0c12#

可以使用stringutils.isempty(),如果字符串为null或空,则结果为true。

String str1 = "";
 String str2 = null;

 if(StringUtils.isEmpty(str)){
     System.out.println("str1 is null or empty");
 }

 if(StringUtils.isEmpty(str2)){
     System.out.println("str2 is null or empty");
 }

将导致
str1为空
str2为空

nhaq1z21

nhaq1z2113#

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

或者

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

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

注意:第二个检查(第一个和第二个选项)假设str不为null。这是可以的,因为第一个检查就是这样做的(如果第一个检查为false,java就不做第二个检查)!
重要提示:不要使用==表示字符串相等检查指针是否相等,而不是值。两个字符串可以在不同的内存地址(两个示例)中,但具有相同的值!

yvt65v4c

yvt65v4c14#

使用java 8 optional,您可以执行以下操作:

public Boolean isStringCorrect(String str) {
    return Optional.ofNullable(str)
            .map(String::trim)
            .map(string -> !str.isEmpty())
            .orElse(false);
}

在这个表达式中,您将处理 String 也由空格组成的。

voase2hg

voase2hg15#

根据输入返回true或false

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

相关问题