示例 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
在上面的程序中,我们创建了
- 一个null字符串 str1
- 一个空字符串 str2
- 一个包含空格的字符串 str3
isNullEmpty()
方法用于检查字符串是否为null或空
这里,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。