在Java中检查字符串是否为空或空

我正在解析HTML数据。当要解析的单词不匹配时,String可能是null或空。

所以,我这样写:

if(string.equals(null) || string.equals("")){
Log.d("iftrue", "seem to be true");
}else{
Log.d("iffalse", "seem to be false");
}

当我删除String.equals("")时,它不能正常工作。

我认为String.equals("")不正确。

如何最好地检查空String?

1085387 次浏览

你可以利用Apache Commons StringUtils.isEmpty(str),它会检查空字符串并优雅地处理null

例子:

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

谷歌Guava还提供了一个类似的,可能更容易阅读的方法:Strings.isNullOrEmpty(str)

例子:

System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

检查null或empty或只包含空格的字符串的正确方法是这样的:

if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }

您可以使用Apache commons-lang

StringUtils.isEmpty(String str) -检查字符串是否为空("")或null。

StringUtils.isBlank(String str) -检查字符串是否为空白,空("")或null。

后者认为由空格或特殊字符组成的字符串也为空。参见java.lang.Character.isWhitespace API

import com.google.common.base.Strings;


if(!Strings.isNullOrEmpty(String str)) {
// Do your stuff here
}

这样你可以检查字符串是否不为空,也考虑到空格:

boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
// handle the validation
}