.jpg)
如何检查字符串是否不为空?null
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}

那么 isEmpty() 呢?
if(str != null && !str.isEmpty())
请务必按此顺序使用 的各部分,因为如果第一部分失败,java 将不会继续评估第二部分,从而确保您不会从 if 为 null 中获得空指针异常。&&&&str.isEmpty()str
请注意,它仅在Java SE 1.6之后可用。您必须检查以前的版本。str.length() == 0
要忽略空格,请执行以下操作:
if(str != null && !str.trim().isEmpty())
(因为Java 11可以简化为这也将测试其他Unicode空格)str.trim().isEmpty()str.isBlank()
包装在一个方便的功能中:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
成为:
if( !empty( str ) )

我喜欢使用 Apache commons-lang 来处理这些事情,尤其是 StringUtils 实用程序类:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}

只需在此处添加Android:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
模板简介:该模板名称为【Java 检查字符串是否为空和不为空】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Java】栏目查找您需要的精美模板。