Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

java - 检查字符串是否不为空且不为空(Check whether a string is not null and not empty)

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

(如何检查字符串是否不为null也不为空?)

public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty string */
    }
    /* ... */
}
  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What about isEmpty() ?

(那isEmpty()呢?)

if(str != null && !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将不会继续评估第二部分,因此,如果str为null,则确保不会从str.isEmpty()获得null指针异常。 。)

Beware, it's only available since Java SE 1.6.

(请注意,仅从Java SE 1.6起可用。)

You have to check str.length() == 0 on previous versions.

(您必须在以前的版本中检查str.length() == 0 。)


To ignore whitespace as well:

(也要忽略空格:)

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

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

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

Wrapped in a handy function:

(包裹在一个方便的功能中:)

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

Becomes:

(成为:)

if( !empty( str ) )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...