在 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.