如何检查字符串是否为非空?
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 */
}
/* ... */
}
当前回答
处理字符串中的null更好的方法是,
str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()
简而言之,
str.length()>0 && !str.equalsIgnoreCase("null")
其他回答
如果你使用Spring框架,那么你可以使用method:
org.springframework.util.StringUtils.isEmpty(@Nullable Object str);
该方法接受任何Object作为参数,将其与null和空String进行比较。因此,对于非空的非string对象,此方法永远不会返回true。
你应该使用org.apache.commons.lang3.StringUtils.isNotBlank()或org.apache.commons.lang3.StringUtils.isNotEmpty。这两者之间的决定是基于您实际想要检查的内容。
isNotBlank()检查输入参数是否为:
非空, 不是空字符串("") 不是空白字符序列(" ")
isNotEmpty()只检查输入参数是否为
非空 不是空字符串("")
根据您的实际需要,我建议您选择Guava或Apache Commons。检查我的示例代码中的不同行为:
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
/**
* Created by hu0983 on 2016.01.13..
*/
public class StringNotEmptyTesting {
public static void main(String[] args){
String a = " ";
String b = "";
String c=null;
System.out.println("Apache:");
if(!StringUtils.isNotBlank(a)){
System.out.println(" a is blank");
}
if(!StringUtils.isNotBlank(b)){
System.out.println(" b is blank");
}
if(!StringUtils.isNotBlank(c)){
System.out.println(" c is blank");
}
System.out.println("Google:");
if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
System.out.println(" a is NullOrEmpty");
}
if(Strings.isNullOrEmpty(b)){
System.out.println(" b is NullOrEmpty");
}
if(Strings.isNullOrEmpty(c)){
System.out.println(" c is NullOrEmpty");
}
}
}
结果: Apache: A是空的 B是空白的 C为空白 谷歌: b为NullOrEmpty c为NullOrEmpty
简单地说,忽略空白:
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}
处理字符串中的null更好的方法是,
str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()
简而言之,
str.length()>0 && !str.equalsIgnoreCase("null")