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

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


当前回答

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

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

如果foo为空,将抛出NullPointerException。

其他回答

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

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

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

而不是使用第三方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

@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