温馨提示×

java怎么判断字符串是否为空

小亿
97
2023-12-26 19:37:57
栏目: 编程语言

在Java中,可以使用以下方法来判断字符串是否为空:

  1. 使用length()方法,判断字符串的长度是否为0:
String str = "example";
if (str.length() == 0) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}
  1. 使用isEmpty()方法,判断字符串是否为空字符串(长度为0):
String str = "example";
if (str.isEmpty()) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}
  1. 使用isBlank()方法,判断字符串是否为空或只包含空格:
String str = "example";
if (str.isBlank()) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}

其中,isBlank()方法是在Java 11中引入的,如果使用的是Java 11或更高版本,建议使用该方法来判断字符串是否为空。

0