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

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)之间有区别吗?


当前回答

stringutil的。isBlank对于空格也返回true:

isBlank (String str) 检查字符串是否为空白、空("")或空。

其他回答

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

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

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

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

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

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

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

isBlank()和isEmpty()的唯一区别是:

StringUtils.isBlank(" ")       = true //compared string value has space and considered as blank

StringUtils.isEmpty(" ")       = false //compared string value has space and not considered as empty

底线是:

isEmpty take " " as a character but isBlank not. Rest both are same.

@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