检查字符串是否为空且不为空 [英] Check whether a string is not null and not empty
问题描述
如何检查字符串是否为空且不为空?
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 */
}
/* ... */
}
推荐答案
if(str != null && !str.isEmpty())
请务必使用的部分&&&
按此顺序,因为如果&&
的第一部分失败,java将不会继续评估第二部分,因此确保您不会从 str.isEmpty()
获取空指针异常,如果 str
为空。
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屋!