String.isBlank() 替换

问题描述 投票:0回答:6

我正在尝试修改使用

String.isBlank(text)
的代码。这个方法是Java 11中引入的,但是我当前的项目使用Java 8,我不想升级。是否有
isBlank
方法的源代码或者如何替换它?

我尝试创建一个方法,但我不确定应该在那里进行什么检查:

/**
 * @param text - the text to check
 * @return {@code true} if {@code text} is empty or contains only white space codepoints
 */
public static final boolean isBlank(final String text)
{
    if (text == null || text.isEmpty())
    {
        return true;
    }
    
    for (final char c : text.toCharArray())
    {
        //Check here
    }
    
    return false;
}
java
6个回答
5
投票

在类org.apache.commons.lang3.StringUtils中,函数isBlank是这样的:

public static boolean isBlank(final CharSequence cs) {
    int strLen;
    if (cs == null || (strLen = cs.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(cs.charAt(i))) {
            return false;
        }
    }
    return true;
}

它适用于 Java 8,您只需导入它即可


4
投票

Java 11 之前:

string.trim().isEmpty();

所以,如果你想包装 isBlank 函数,你可以这样做:

public static final boolean isBlank(final String text) {
    return text == null || text.trim().isEmpty();
} 

2
投票

我和你有同样的问题,一个 Java 11 项目,我不得不降级到 Java 8。你可以在你的项目中导入 Apache Commons:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

那么你只需调用 StringUtils.isBlank(string) 它将返回 true 或 false


0
投票

您可以使用 Guava 库,并且

Strings.nullToEmpty(str).trim().isEmpty()

复制 isBlank 行为。


0
投票

除了其他答案(导入库)之外,您还可以在 StringUtils 类中定义自己的函数,然后可以添加任何其他 String utils 操作。

您想要的当前方法如下所示:


public static boolean isNullOrEmpty(String text) {
        boolean isNull = true;
        if (text != null) {
            if (!text.trim().equals("")) {
                isNull = false;
            }
        }
        return isNull;
    }

此外,通过这个你不必导入任何库


0
投票

Spring 有一个

org.springframework.util.StringUtils.hasText(str)
方法。

检查给定的字符串是否包含实际文本。

更具体地说,如果 String 不为 null、长度大于 0 并且至少包含一个非空白字符,则此方法返回 true。

所以你可以使用:

! StringUtils.hasText(str)

检查字符串是否为空。

© www.soinside.com 2019 - 2024. All rights reserved.