如何检查字符串是否为非空?
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-11中有一个新方法:String#isBlank
如果字符串为空或只包含空白代码点则返回true,否则返回false。
jshell> "".isBlank()
$7 ==> true
jshell> " ".isBlank()
$8 ==> true
jshell> " ! ".isBlank()
$9 ==> false
这可以与Optional结合起来检查字符串是否为null或空
boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);
字符串#是空白
其他回答
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
...
}
使用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()));
}
在这里添加Android:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
你可以使用函数式检查:
Optional.ofNullable(str)
.filter(s -> !(s.trim().isEmpty()))
.ifPresent(result -> {
// your query setup goes here
});