本文翻译自:Checking if a string is empty or null in Java [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- Check whether a string is not null and not empty 30 answers 检查字符串是否为空且不为空 30个答案
I'm parsing HTML data. 我正在解析HTML数据。 The String
may be null
or empty, when the word to parse does not match. 当要解析的单词不匹配时, String
可以为null
或为空。
So, I wrote it like this: 所以,我这样写了:
if(string.equals(null) || string.equals("")){
Log.d("iftrue", "seem to be true");
}else{
Log.d("iffalse", "seem to be false");
}
When I delete String.equals("")
, it does not work correctly. 当我删除String.equals("")
,它无法正常工作。
I thought String.equals("")
wasn't correct. 我以为String.equals("")
不正确。
How can I best check for an empty String
? 我怎样才能最好地检查空String
?
#1楼
参考:https://stackoom.com/question/zlht/检查Java中的字符串是空还是空-重复
#2楼
You can leverage Apache Commons StringUtils.isEmpty(str)
, which checks for empty strings and handles null
gracefully. 您可以利用Apache Commons StringUtils.isEmpty(str)
,它检查空字符串并优雅地处理null
。
Example: 例:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str)
. Google Guava还提供了一种类似的,可能更容易阅读的方法: Strings.isNullOrEmpty(str)
。
Example: 例:
System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true
#3楼
检查null或空的正确方法如下:
if(str != null && !str.isEmpty()) { /* do your stuffs here */ }
#4楼
You can use Apache commons-lang 您可以使用Apache commons-lang
StringUtils.isEmpty(String str)
- Checks if a String is empty ("") or null. StringUtils.isEmpty(String str)
- 检查String是否为空(“”)或null。
or 要么
StringUtils.isBlank(String str)
- Checks if a String is whitespace, empty ("") or null. StringUtils.isBlank(String str)
- 检查String是否为空格,空(“”)或null。
the latter considers a String which consists of spaces or special characters eg " " empty too. 后者考虑一个由空格或特殊字符组成的字符串,例如“”也是空的。 See java.lang.Character.isWhitespace API 请参阅java.lang.Character.isWhitespace API
#5楼
import com.google.common.base
if(!Strings.isNullOrEmpty(String str)) {
// Do your stuff here
}
#6楼
This way you check if the string is not null and not empty, also considering the empty spaces: 这样你检查字符串是否为空而不是空,也考虑空格:
boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
// handle the validation
}