如何检查字符串是否为非空?
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 */
}
/* ... */
}
当前回答
我已经制作了自己的实用函数来一次检查几个字符串,而不是有一个充满if(str != null && !str的if语句。= null && !str2.isEmpty)。这是函数:
public class StringUtils{
public static boolean areSet(String... strings)
{
for(String s : strings)
if(s == null || s.isEmpty)
return false;
return true;
}
}
所以我可以简单地写:
if(!StringUtils.areSet(firstName,lastName,address)
{
//do something
}
其他回答
我已经制作了自己的实用函数来一次检查几个字符串,而不是有一个充满if(str != null && !str的if语句。= null && !str2.isEmpty)。这是函数:
public class StringUtils{
public static boolean areSet(String... strings)
{
for(String s : strings)
if(s == null || s.isEmpty)
return false;
return true;
}
}
所以我可以简单地写:
if(!StringUtils.areSet(firstName,lastName,address)
{
//do something
}
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
...
}
这对我来说很管用:
import com.google.common.base.Strings;
if (!Strings.isNullOrEmpty(myString)) {
return myString;
}
如果给定字符串为null或为空字符串,则返回true。 考虑用nullToEmpty规范字符串引用。如果你 做,你可以使用String.isEmpty()而不是这个方法,你不会吗 需要特殊的零安全形式的方法,如String.toUpperCase 要么。或者,如果你想“从另一个方向”正常化, 将空字符串转换为null,可以使用emptyToNull。
如果有人使用springboot,那么下面的选项可能会有帮助,
import static org.springframework.util.StringUtils.hasLength;
if (hasLength(str)) {
// do stuff
}
加上@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是奇怪的”)。