示例 1: 检查字符串是否为空或 Null
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
在上面的程序中,我们已经创建了
空字符串 str1
空字符串 str2
带有空格的字符串 str3
方法 isNullEmpty()
检查字符串是否为空或空
这里,
str3 只包含空格。但是,程序并不认为它是一个空字符串。
这是因为在 Java 中空格被视为字符,并且带有空格的字符串是常规字符串。
现在,如果我们希望程序将带有空格的字符串视为空字符串,我们可以使用
trim()
方法。该方法删除字符串中存在的所有空格。
示例 2: 检查带空格的字符串是否为空或 Null
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()
方法。这将
因此,我们得到 str is EMPTY 作为输出。