Java 检查字符串是否不为空且不为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3598770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:27:35  来源:igfitidea点击:

Check whether a string is not null and not empty

javastringstring-comparison

提问by

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 */
    }
    /* ... */
}

采纳答案by Colin Hebert

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 stris null.

请务必&&按此顺序使用的部分,因为如果第一部分&&失败,java 将不会继续评估第二部分,从而确保您不会从str.isEmpty()if stris null 中获得空指针异常。

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

请注意,它仅从 Java SE 1.6 开始可用。您必须检查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 11str.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 ) )

回答by helios

str != null && str.length() != 0

alternatively

或者

str != null && !str.equals("")

or

或者

str != null && !"".equals(str)

Note: The second check (first and second alternatives) assumes str is not null. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!

注意:第二个检查(第一个和第二个选项)假定 str 不为空。没关系,因为第一次检查是这样做的(如果第一次检查为假,Java 不会进行第二次检查)!

IMPORTANT: DON'T use == for string equality. == checks the pointer is equal, not the value. Two strings can be in different memory addresses (two instances) but have the same value!

重要提示:不要将 == 用于字符串相等。== 检查指针是否相等,而不是值。两个字符串可以位于不同的内存地址(两个实例)但具有相同的值!

回答by codaddict

How about:

怎么样:

if(str!= null && str.length() != 0 )

回答by Romain Linsolas

Use org.apache.commons.lang.StringUtils

使用org.apache.commons.lang.StringUtils

I like to use Apache commons-langfor these kinds of things, and especially the StringUtilsutility class:

我喜欢将 Apache commons-lang用于这些类型的事情,尤其是StringUtils实用程序类:

import org.apache.commons.lang.StringUtils;

if (StringUtils.isNotBlank(str)) {
    ...
} 

if (StringUtils.isBlank(str)) {
    ...
} 

回答by Sean Patrick Floyd

Almost every library I know defines a utility class called StringUtils, StringUtilor StringHelper, and they usually include the method you are looking for.

我知道的几乎每个库都定义了一个名为StringUtils, StringUtilor的实用程序类StringHelper,它们通常包含您正在寻找的方法。

My personal favorite is Apache Commons / Lang, where in the StringUtilsclass, you get both the

我个人最喜欢的是Apache Commons / Lang,在StringUtils类中,您可以同时获得

  1. StringUtils.isEmpty(String)and the
  2. StringUtils.isBlank(String)method

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

  1. StringUtils.isEmpty(String)
  2. StringUtils.isBlank(String)方法

(第一个检查字符串是否为空或空,第二个检查它是否为空、空或空格)

There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.

Spring、Wicket 和许多其他库中也有类似的实用程序类。如果您不使用外部库,您可能希望在您自己的项目中引入一个 StringUtils 类。



Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string)method.

更新:很多年过去了,现在我建议使用GuavaStrings.isNullOrEmpty(string)方法。

回答by BjornS

As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;

正如 seanizer 上面所说,Apache StringUtils 在这方面非常棒,如果您要包含番石榴,您应该执行以下操作;

public List<Employee> findEmployees(String str, int dep) {
 Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
 /** code here **/
}

May I also recommend that you refer to the columns in your result set by name rather than by index, this will make your code much easier to maintain.

我还建议您按名称而不是按索引引用结果集中的列,这将使您的代码更易于维护。

回答by A Null Pointer

Use Apache StringUtils' isNotBlank method like

使用 Apache StringUtils 的 isNotBlank 方法,例如

StringUtils.isNotBlank(str)

It will return true only if the str is not null and is not empty.

仅当 str 不为 null 且不为空时,它才会返回 true。

回答by Adam Gent

To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:

添加到@BJorn 和@SeanPatrickFloyd Guava 方法是:

Strings.nullToEmpty(str).isEmpty(); 
// or
Strings.isNullOrEmpty(str);

Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank()(as in what is whitespace or not).

Commons Lang 有时更具可读性,但我一直在慢慢地更多地依赖 Guava 加上有时 Commons Lang 在涉及到时isBlank()(如空白与否)令人困惑。

Guava's version of Commons Lang isBlankwould be:

Guava 的 Commons Lang 版本isBlank将是:

Strings.nullToEmpty(str).trim().isEmpty()

I will say code that doesn't allow ""(empty) ANDnullis suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing nullmakes sense (although for SQL I can understand as SQL/HQL is weird about '').

我会说不允许""(空)并且null是可疑的并且可能有问题的代码,因为它可能无法处理所有不允许的情况null(尽管对于 SQL 我可以理解,因为 SQL/HQL 很奇怪'')。

回答by phreakhead

Just adding Android in here:

只需在此处添加 Android:

import android.text.TextUtils;

if (!TextUtils.isEmpty(str)) {
...
}

回答by Tom

If you don't want to include the whole library; just include the code you want from it. You'll have to maintain it yourself; but it's a pretty straight forward function. Here it is copied from commons.apache.org

如果您不想包含整个库;只需包含您想要的代码。你必须自己维护它;但这是一个非常直接的功能。这里是从commons.apache.org复制的

    /**
 * <p>Checks if a String is whitespace, empty ("") or null.</p>
 *
 * <pre>
 * StringUtils.isBlank(null)      = true
 * StringUtils.isBlank("")        = true
 * StringUtils.isBlank(" ")       = true
 * StringUtils.isBlank("bob")     = false
 * StringUtils.isBlank("  bob  ") = false
 * </pre>
 *
 * @param str  the String to check, may be null
 * @return <code>true</code> if the String is null, empty or whitespace
 * @since 2.0
 */
public static boolean isBlank(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if ((Character.isWhitespace(str.charAt(i)) == false)) {
            return false;
        }
    }
    return true;
}