在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP