如何检查字符串是否为非空?
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 */
}
/* ... */
}
当前回答
在这里添加Android:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
其他回答
如果您正在使用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
简单地说,忽略空白:
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}
我已经制作了自己的实用函数来一次检查几个字符串,而不是有一个充满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
}
str != null && str.length() != 0
另外
str != null && !str.equals("")
or
str != null && !"".equals(str)
注意:第二次检查(第一个和第二个替代)假设str不为空。这只是因为第一次检查是这样做的(如果第一次检查为假,Java不会进行第二次检查)!
重要:不要用==表示字符串相等。==检查指针是否相等,而不是值。两个字符串可以在不同的内存地址(两个实例),但具有相同的值!
根据输入返回true或false
Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);