我遇到了一些代码,有以下:

String foo = getvalue("foo");
if (StringUtils.isBlank(foo))
    doStuff();
else
    doOtherStuff();

这似乎在功能上等同于以下内容:

String foo = getvalue("foo");
if (foo.isEmpty())
    doStuff();
else
    doOtherStuff();

这两者(org.apache.commons.lang3.StringUtils.isBlank和java.lang.String.isEmpty)之间有区别吗?


当前回答

我回答这个问题是因为它是谷歌的“字符串isBlank()方法”的顶部结果。

如果使用Java 11或以上版本,可以使用String类isBlank()方法。这个方法的作用与Apache Commons StringUtils类相同。

我已经写了一个关于这个方法的例子的小帖子,在这里阅读。

其他回答

@arshajii的回答完全正确。但是,我要更明确地说,

StringUtils.isBlank()

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true  
 StringUtils.isBlank(" ")       = true  
 StringUtils.isBlank("bob")     = false  
 StringUtils.isBlank("  bob  ") = false

StringUtils.isEmpty

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true  
 StringUtils.isEmpty(" ")       = false  
 StringUtils.isEmpty("bob")     = false  
 StringUtils.isEmpty("  bob  ") = false

而不是使用第三方lib,使用Java 11 isBlank()

    String str1 = "";
    String str2 = "   ";
    Character ch = '\u0020';
    String str3 =ch+" "+ch;

    System.out.println(str1.isEmpty()); //true
    System.out.println(str2.isEmpty()); //false
    System.out.println(str3.isEmpty()); //false            

    System.out.println(str1.isBlank()); //true
    System.out.println(str2.isBlank()); //true
    System.out.println(str3.isBlank()); //true

我回答这个问题是因为它是谷歌的“字符串isBlank()方法”的顶部结果。

如果使用Java 11或以上版本,可以使用String类isBlank()方法。这个方法的作用与Apache Commons StringUtils类相同。

我已经写了一个关于这个方法的例子的小帖子,在这里阅读。

StringUtils isEmpty = String isEmpty检查+检查null。

StringUtils isBlank = StringUtils isEmpty检查+检查文本是否只包含空白字符。

有关进一步调查的有用连结:

StringUtils是空白文档 StringUtils isEmpty文档 字符串isEmpty文档

StringUtils.isBlank()对于空格(只是空格)和null String也返回true。实际上,它修饰Char序列,然后执行检查。

当String参数中没有charsequence或String参数为null时,StringUtils.isEmpty()返回true。不同的是,如果字符串参数只包含whiltespaces, isEmpty()返回false。它认为空白是一种非空状态。