在 Java 中检查一个字符串是否是空白、空字符串("")或 null


假设我们的字符串如下。

String myStr = "";

现在,我们将检查上述字符串是否是空白、空字符串("")或 null。

if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {
   System.out.println("String is not null or not empty or not whitespace");
} else {
   System.out.println("String is null or empty or whitespace");
}

以下是检查空字符串的一个示例。

示例

 实际演示

public class Demo {
   public static void main(String[] args) {
      String myStr = "";
      if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {
         System.out.println("String is not null or not empty or not whitespace");
      } else {
         System.out.println("String is null or empty or whitespace");
      }
   }
}

输出

String is null or empty or whitespace

让我们看另一个检查空白输入的示例。

示例

 实际演示

public class Demo {
   public static void main(String[] args) {
      String myStr = " ";
      if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {
         System.out.println("String is not null or not empty or not whitespace");
      } else {
         System.out.println("String is null or empty or whitespace");
      }
   }
}

输出

String is null or empty or whitespace

更新时间:27-Jun-2020

2K+ 次浏览

开启你的职业生涯

通过完成课程取得认证

立即开始
广告
© . All rights reserved.