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

  1. 使用length()方法判断字符串的长度是否为0:
String str = "example";
if (str.length() == 0) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串非空");
}
  1. 使用isEmpty()方法判断字符串是否为空:
String str = "example";
if (str.isEmpty()) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串非空");
}
  1. 使用isBlank()方法判断字符串是否为空或只包含空白字符(Java 11及以上版本):
String str = "example";
if (str.isBlank()) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串非空");
}

其中,isEmpty()方法和isBlank()方法的区别在于,isEmpty()方法只判断字符串是否为空,而isBlank()方法还会判断字符串是否只包含空白字符(如空格、制表符、换行符等)

java String非空判断

原文地址: https://www.cveoy.top/t/topic/ifSu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录