如何检查字符串是否为非空?
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 */
}
/* ... */
}
当前回答
如果有人使用springboot,那么下面的选项可能会有帮助,
import static org.springframework.util.StringUtils.hasLength;
if (hasLength(str)) {
// do stuff
}
其他回答
我已经制作了自己的实用函数来一次检查几个字符串,而不是有一个充满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
}
你可以使用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或空
使用Apache StringUtils的isNotBlank方法
StringUtils.isNotBlank(str)
只有当str不为空时,它才会返回true。
我遇到过一种情况,我必须检查“null”(作为字符串)必须被视为空。空格和实际null必须返回true。 我最终确定了下面的函数…
public boolean isEmpty(String testString) {
return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}
测试等于一个空字符串和null在相同的条件:
if(!"".equals(str) && str != null) {
// do stuff.
}
如果str为空则不抛出NullPointerException,因为Object.equals()如果arg为空则返回false。
另一个构造str.equals("")会抛出可怕的NullPointerException。有些人可能认为在调用equals()时使用String字面值作为对象是一种糟糕的形式,但它确实完成了这项工作。
还有这个答案:https://stackoverflow.com/a/531825/1532705