一、概述
如何检查字符串是否不为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不会继续评估第二部分,从而确保您不会从str.isEmpty()
ifstr
为null时得到null指针异常。
请注意,仅从Java SE 1.6起可用。您必须检查str.length() == 0
以前的版本。
也要忽略空格:
if(str != null && !str.trim().isEmpty())
(由于Java 11str.trim().isEmpty()
可以简化为str.isBlank()
也可以测试其他Unicode空白)
包裹在一个方便的功能中:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
成为:
if( !empty( str ) )
如若转载,请注明出处:https://www.javaidea.cn/article/8333.html