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

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()和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

其他回答

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

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

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

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

StringUtils.isBlank(foo)将为您执行空检查。如果你执行foo. isempty()并且foo为空,你将引发一个NullPointerException。

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

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

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

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

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

StringUtils.isBlank()也会检查null,然而:

String foo = getvalue("foo");
if (foo.isEmpty())

如果foo为空,将抛出NullPointerException。