使用 Java 程序来检查一个字符串是否为空

在本程序中,您将学习使用 Java 中的方法和 if-else 语句检查字符串是否为空或 null。

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:检查字符串是否为空或 Null

public class Main {
  public static void main(String[] args) {

    // create null, empty, and regular strings
    String str1 = null;
    String str2 = "";
    String str3 = "  ";

    // check if str1 is null or empty
    System.out.println("str1 is " + isNullEmpty(str1));

    // check if str2 is null or empty
    System.out.println("str2 is " + isNullEmpty(str2));

    // check if str3 is null or empty
    System.out.println("str3 is " + isNullEmpty(str3));
  }

  // method check if string is null or empty
  public static String isNullEmpty(String str) {

    // check if string is null
    if (str == null) {
      return "NULL";
    }

    // check if string is empty
    else if(str.isEmpty()){
      return "EMPTY";
    }

    else {
      return "neither NULL nor EMPTY";
    }
  }
}

输出

str1 is NULL
str2 is EMPTY
str3 is neither NULL nor EMPTY

在上面的程序中,我们创建了

  • null 字符串 str1
  • 空字符串 str2
  • 带有空格的字符串 str3
  • 方法 isNullEmpty() 来检查字符串是否为 null 或空

这里, str3 仅由空格组成。但是,程序并不认为它是一个空字符串。

这是因为空格在 Java 中被视为字符,并且带有空格的字符串是常规字符串。

现在,如果我们希望程序将带有空格的字符串视为空字符串,我们可以使用 trim() 方法。该方法删除字符串头尾存在的所有空格。

示例 2:检查带空格的字符串是 Empty 还是 Null

public class Main {
  public static void main(String[] args) {

    // create a string with white spaces
    String str = "    ";

    // check if str1 is null or empty
    System.out.println("str is " + isNullEmpty(str));
  }

  // method check if string is null or empty
  public static String isNullEmpty(String str) {

    // check if string is null
    if (str == null) {
      return "NULL";
    }

    // check if string is empty
    else if (str.trim().isEmpty()){
      return "EMPTY";
    }

    else {
      return "neither NULL nor EMPTY";
    }
  }
}

输出

str is EMPTY

在上面的例子中,注意检查空字符串的条件

else if (str.trim().isEmpty())

在这里,我们在 isEmpty() 方法之前使用了 trim() 方法。这会

  1. 删除字符串头尾的所有空格
  2. 检查字符串是否为空

因此,我们得到 str is EMPTY 作为输出。