如何检查字符串是否不是null
并且不为空?
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.isEmpty())
请务必使用以下部件&&
按照这个顺序,因为如果第一部分是,java将不会继续计算第二部分&&
失败,从而确保您不会得到空指针异常str.isEmpty()
if str
一片空白。
请注意,它仅从 Java SE 1.6 起可用。你必须检查str.length() == 0
在以前的版本上。
也可以忽略空格:
if(str != null && !str.trim().isEmpty())
(从 Java 11 开始str.trim().isEmpty()
可以减少到str.isBlank()
这也将测试其他 Unicode 空格)
封装在一个方便的函数中:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
Becomes:
if( !empty( str ) )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)