如何检查字符串是否为非空?

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

当前回答

测试等于一个空字符串和null在相同的条件:

if(!"".equals(str) && str != null) {
    // do stuff.
}

如果str为空则不抛出NullPointerException,因为Object.equals()如果arg为空则返回false。

另一个构造str.equals("")会抛出可怕的NullPointerException。有些人可能认为在调用equals()时使用String字面值作为对象是一种糟糕的形式,但它确实完成了这项工作。

还有这个答案:https://stackoverflow.com/a/531825/1532705

其他回答

那么isEmpty()呢?

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

请确保按此顺序使用&&的部分,因为如果&&的第一部分失败,java将不会继续计算第二部分,从而确保如果str为空,则不会从str. isempty()获得空指针异常。

注意,它只在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();
}

就变成:

if( !empty( str ) )

要检查字符串是否为空,可以检查它是否为空,但这不能说明有空格的字符串。您可以使用str.trim()来修剪所有空白,然后链接. isempty()以确保结果不为空。

    if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }

如何:

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

使用Apache StringUtils的isNotBlank方法

StringUtils.isNotBlank(str)

只有当str不为空时,它才会返回true。

根据您的实际需要,我建议您选择Guava或Apache Commons。检查我的示例代码中的不同行为:

import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;

/**
 * Created by hu0983 on 2016.01.13..
 */
public class StringNotEmptyTesting {
  public static void main(String[] args){
        String a = "  ";
        String b = "";
        String c=null;

    System.out.println("Apache:");
    if(!StringUtils.isNotBlank(a)){
        System.out.println(" a is blank");
    }
    if(!StringUtils.isNotBlank(b)){
        System.out.println(" b is blank");
    }
    if(!StringUtils.isNotBlank(c)){
        System.out.println(" c is blank");
    }
    System.out.println("Google:");

    if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
        System.out.println(" a is NullOrEmpty");
    }
    if(Strings.isNullOrEmpty(b)){
        System.out.println(" b is NullOrEmpty");
    }
    if(Strings.isNullOrEmpty(c)){
        System.out.println(" c is NullOrEmpty");
    }
  }
}

结果: Apache: A是空的 B是空白的 C为空白 谷歌: b为NullOrEmpty c为NullOrEmpty