如何检查字符串是否为非空?
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 */
}
/* ... */
}
当前回答
如果您正在使用Java 8并希望采用更函数式编程的方法,您可以定义一个函数来管理控件,然后您可以重用它并在需要时应用()。
在实践中,您可以将函数定义为
Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)
然后,你可以通过简单地调用apply()方法来使用它:
String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true
如果您愿意,您可以定义一个函数来检查String是否为空,然后用!对其求反。
在这种情况下,函数看起来像:
Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)
然后,你可以通过简单地调用apply()方法来使用它:
String emptyString = "";
!isEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true
其他回答
根据您的实际需要,我建议您选择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
正如seanizer上面所说,Apache StringUtils在这方面非常出色,如果你要包括guava,你应该做以下工作;
public List<Employee> findEmployees(String str, int dep) {
Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
/** code here **/
}
我还建议您通过名称而不是索引来引用结果集中的列,这将使您的代码更容易维护。
如果你使用Spring框架,那么你可以使用method:
org.springframework.util.StringUtils.isEmpty(@Nullable Object str);
该方法接受任何Object作为参数,将其与null和空String进行比较。因此,对于非空的非string对象,此方法永远不会返回true。
使用org.apache.commons.lang.StringUtils
我喜欢用Apache common -lang来做这些事情,尤其是StringUtils实用程序类:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}
你应该使用org.apache.commons.lang3.StringUtils.isNotBlank()或org.apache.commons.lang3.StringUtils.isNotEmpty。这两者之间的决定是基于您实际想要检查的内容。
isNotBlank()检查输入参数是否为:
非空, 不是空字符串("") 不是空白字符序列(" ")
isNotEmpty()只检查输入参数是否为
非空 不是空字符串("")