如何检查字符串是否不为null也不为空? android
public void doStuff(String str) { if (str != null && str != "**here I want to check the 'str' is empty or not**") { /* handle empty string */ } /* ... */ }
添加到@BJorn和@SeanPatrickFloyd Guava的方法是: apache
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对''
)很奇怪。 google
只需在此处添加Android: spa
import android.text.TextUtils; if (!TextUtils.isEmpty(str)) { ... }
若是您不想包括整个库; 只需包含您想要的代码便可。 您必须本身维护它; 但这是一个很是简单的功能。 这里是从commons.apache.org复制的 code
/** * <p>Checks if a String is whitespace, empty ("") or null.</p> * * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> 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; }
测试等于空字符串,而且在相同条件下为null: 对象
if(!"".equals(str) && str != null) { // do stuff. }
若是str为null,则不抛出NullPointerException
,由于若是arg为null
,则Object.equals()
返回false。 字符串
其余构造str.equals("")
将抛出可怕的NullPointerException
。 有些人可能会认为使用String文字的格式很糟糕,由于调用equals()
时的对象被调用了,可是它确实起做用。 get
还要检查此答案: https : //stackoverflow.com/a/531825/1532705
这对我有用:
import com.google.common.base.Strings; if (!Strings.isNullOrEmpty(myString)) { return myString; }
若是给定的字符串为null或为空字符串,则返回true。
考虑使用nullToEmpty标准化字符串引用。 若是这样作,则可使用String.isEmpty()代替此方法,而且您也不须要特殊的null安全形式的方法,例如String.toUpperCase。 或者,若是您但愿“从另外一个方向”进行归一化,将空字符串转换为null,则可使用emptyToNull。