我正在解析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
发布于 2013-02-06 12:14:37
检查null或空或仅包含空格的字符串的正确方法如下所示:
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
发布于 2013-02-06 12:14:27
您可以利用Apache Commons StringUtils.isEmpty(str)
,它可以检查空字符串并优雅地处理null
。
示例:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Google Guava还提供了一个类似的、可能更容易阅读的方法:Strings.isNullOrEmpty(str)
。
示例:
System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true
发布于 2013-02-06 12:28:38
您可以使用Apache commons-lang
StringUtils.isEmpty(String str)
-检查字符串是否为空("")或null。
或
StringUtils.isBlank(String str)
-检查字符串是空白、空("")还是null。
后者认为由空格或特殊字符组成的字符串也是空的。请参阅java.lang.Character.isWhitespace API
https://stackoverflow.com/questions/14721397
复制相似问题