如何检查字符串是否不为null也不为空?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
#1楼
添加到@BJorn和@SeanPatrickFloyd Guava的方法是:
Strings.nullToEmpty(str).isEmpty();
// or
Strings.isNullOrEmpty(str);
Commons Lang有时更具可读性,但我一直在慢慢地更多地依赖Guava,有时在谈到isBlank()时,Commons Lang有时会造成混乱(例如是否有空格)。
Guava的Commons Lang isBlank版本为:
Strings.nullToEmpty(str).trim().isEmpty()
我会说不允许使用"" (空) 和 null是可疑的,并且有潜在的bug,因为它可能无法处理不允许使用null所有情况(尽管对于SQL,我可以理解为SQL / HQL对'' )很奇怪。
#2楼
只需在此处添加Android:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
#3楼
如果您不想包括整个库; 只需包含您想要的代码即可。 您必须自己维护它; 但这是一个非常简单的功能。 这里是从commons.apache.org复制的
/**
*
Checks if a String is whitespace, empty ("") or null.
*
*
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
*
*
* @param str the String to check, may be null
* @return true
if the String is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
#4楼
测试等于空字符串,并且在相同条件下为null:
if(!"".equals(str) && str != null) {
// do stuff.
}
如果str为null,则不抛出NullPointerException ,因为如果arg为null ,则Object.equals()返回false。
其他构造str.equals("")将抛出可怕的NullPointerException 。 有些人可能会认为使用String文字的格式很糟糕,因为调用equals()时的对象被调用了,但是它确实起作用。
#5楼
这对我有用:
import com.google.common.base.Strings;
if (!Strings.isNullOrEmpty(myString)) {
return myString;
}
如果给定的字符串为null或为空字符串,则返回true。
考虑使用nullToEmpty标准化字符串引用。 如果这样做,则可以使用String.isEmpty()代替此方法,并且您也不需要特殊的null安全形式的方法,例如String.toUpperCase。 或者,如果您希望“从另一个方向”进行归一化,将空字符串转换为null,则可以使用emptyToNull。