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

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也返回true。实际上,它修饰Char序列,然后执行检查。

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

其他回答

StringUtils.isBlank(myStr)检查String myStr是否为空白,空("")或null。

底线是:

isEmpty take " " as a character but isBlank not. Rest both are same.
public static boolean isEmpty(String ptext) {
 return ptext == null || ptext.trim().length() == 0;
}

public static boolean isBlank(String ptext) {
 return ptext == null || ptext.trim().length() == 0;
}

两者都有相同的代码如何isBlank处理空白可能你指的是isBlankString,它有处理空白的代码。

public static boolean isBlankString( String pString ) {
 int strLength;
 if( pString == null || (strLength = pString.length()) == 0)
 return true;
 for(int i=0; i < strLength; i++)
 if(!Character.isWhitespace(pString.charAt(i)))
 return false;
 return false;
}

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

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

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

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

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

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

如果foo为空,将抛出NullPointerException。