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

  1. 使用equals()方法判断字符串是否为空字符串:
String str = "Hello";
if (str.equals("")) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}
  1. 使用isEmpty()方法判断字符串是否为空字符串:
String str = "Hello";
if (str.isEmpty()) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}
  1. 使用trim()方法去除字符串两端的空格,然后判断是否为空:
String str = "   ";
if (str.trim().isEmpty()) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}

注意:以上方法都是判断字符串是否为空字符串,即长度为0的字符串。如果要判断字符串是否为null,可以使用以下方法:

String str = null;
if (str == null) {
    System.out.println("字符串为空");
} else {
    System.out.println("字符串不为空");
}
``
java中判断字符串是否为空的方法

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

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