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

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类相同。

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

其他回答

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

System.out.println("".isEmpty());                      //true
System.out.println(" ".isEmpty());                     //false
System.out.println(('\u0020'+" "+'\u0020').isEmpty()); //false

System.out.println("".isBlank());                      //true
System.out.println(" ".isBlank());                     //true
System.out.println(('\u0020'+" "+'\u0020').isBlank()); //true

如果你想使用Java 8并且需要isBlank函数,那么尝试使用第三方库org.apache.commons.lang3.StringUtils

StringUtils.isBlank()

System.out.println(StringUtils.isBlank(null));      //true
System.out.println(StringUtils.isBlank(""));        //true
System.out.println(StringUtils.isBlank(" "));       //true
System.out.println(StringUtils.isBlank("bob"));     //false
System.out.println(StringUtils.isBlank("  bob  ")); //false

StringUtils.isEmpty

System.out.println(StringUtils.isEmpty(null));      // = true
System.out.println(StringUtils.isEmpty(""));        //= true
System.out.println(StringUtils.isEmpty(" "));       // = false
System.out.println(StringUtils.isEmpty("foo"));     // = false
System.out.println(StringUtils.isEmpty("  foo  ")); //= false

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

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

如果foo为空,将抛出NullPointerException。

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

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