如何检查字符串是否为非空?
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
}
其他回答
正如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 **/
}
我还建议您通过名称而不是索引来引用结果集中的列,这将使您的代码更容易维护。
要检查字符串是否为空,可以检查它是否为空,但这不能说明有空格的字符串。您可以使用str.trim()来修剪所有空白,然后链接. isempty()以确保结果不为空。
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
使用Apache StringUtils的isNotBlank方法
StringUtils.isNotBlank(str)
只有当str不为空时,它才会返回true。
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
...
}
如果您正在使用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