如何检查字符串是否为非空?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
如何检查字符串是否为非空?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
当前回答
在这里添加Android:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
其他回答
你可以使用StringUtils.isEmpty(),如果字符串是空的或空的,则结果为true。
String str1 = "";
String str2 = null;
if(StringUtils.isEmpty(str)){
System.out.println("str1 is null or empty");
}
if(StringUtils.isEmpty(str2)){
System.out.println("str2 is null or empty");
}
会导致
Str1为空或空
Str2为null或空
加上@BJorn和@SeanPatrickFloyd的番石榴方法是:
Strings.nullToEmpty(str).isEmpty();
// or
Strings.isNullOrEmpty(str);
Commons Lang有时更具可读性,但我已经慢慢地更多地依赖于Guava,有时Commons Lang在涉及到isBlank()时令人困惑(如什么是空白或不是空白)。
Guava版本的Commons Lang isBlank将是:
Strings.nullToEmpty(str).trim().isEmpty()
我会说,代码不允许“”(空)和null是可疑的,潜在的bug,因为它可能无法处理所有不允许null有意义的情况(尽管对于SQL,我可以理解为SQL/HQL是奇怪的”)。
str != null && str.length() != 0
另外
str != null && !str.equals("")
or
str != null && !"".equals(str)
注意:第二次检查(第一个和第二个替代)假设str不为空。这只是因为第一次检查是这样做的(如果第一次检查为假,Java不会进行第二次检查)!
重要:不要用==表示字符串相等。==检查指针是否相等,而不是值。两个字符串可以在不同的内存地址(两个实例),但具有相同的值!
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
...
}
使用Apache StringUtils的isNotBlank方法
StringUtils.isNotBlank(str)
只有当str不为空时,它才会返回true。