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

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(myStr)检查String myStr是否为空白,空("")或null。

其他回答

而不是使用第三方库,使用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()检查字符串中的每个字符是否为空白字符(或者字符串为空或为空)。这与仅仅检查字符串是否为空完全不同。

从链接的文档:

检查字符串是否为空白、空("")或空。 StringUtils.isBlank(null) = true StringUtils.isBlank("") = true stringutil的。isBlank(" ") = true StringUtils.isBlank("bob") = false stringutil的。isBlank(" bob ") = false

比较StringUtils.isEmpty:

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

警告:在java.lang.String.isBlank()和java.lang.String.isEmpty()中,除了它们不为null返回true外,它们的工作原理是一样的。

Java .lang. string . isblank()(自Java 11起)

朗。java字符串isEmpty()。

底线是:

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

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

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

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

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