检查字符串是否不为空且不为空 [英] Check whether a string is not null and not empty

查看:39
本文介绍了检查字符串是否不为空且不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字符串是否为空且不为空?

How can I check whether a string is not null and not empty?

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 将不会继续评估第二部分> 失败,从而确保如果 str 为空,您不会从 str.isEmpty() 得到空指针异常.

Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.

请注意,它仅从 Java SE 1.6 开始可用.您必须检查以前版本的 str.length() == 0.

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.

也要忽略空格:

if(str != null && !str.trim().isEmpty())

(自 Java 11 str.trim().isEmpty() 可以简化为 str.isBlank(),这也将测试其他 Unicode 空格)

(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)

包裹在一个方便的函数中:

Wrapped in a handy function:

public static boolean empty( final String s ) {
  // Null-safe, short-circuit evaluation.
  return s == null || s.trim().isEmpty();
}

变成:

if( !empty( str ) )

这篇关于检查字符串是否不为空且不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆