在Java中,可以使用以下方法来判断字符串是否为空:
- 使用
length()方法判断长度是否为0:
String str = "hello";
if (str.length() == 0) {
System.out.println("字符串为空");
}
- 使用
isEmpty()方法判断是否为空字符串:
String str = "hello";
if (str.isEmpty()) {
System.out.println("字符串为空");
}
- 使用
trim()方法去除字符串前后的空格,然后再判断是否为空:
String str = " ";
if (str.trim().isEmpty()) {
System.out.println("字符串为空");
}
以上方法可以用于判断字符串对象是否为空。请注意,如果字符串对象是null,以上方法都会抛出NullPointerException,所以在使用这些方法前,最好先进行null判断。
String str = null;
if (str == null || str.isEmpty()) {
System.out.println("字符串为空");
}
在Java中,可以使用`length()`,`isEmpty()`和`trim().isEmpty()`方法检查字符串是否为空。但需要注意,如果字符串为`null`,这些方法会抛出`NullPointerException`,因此应在使用前进行null检查。
842

被折叠的 条评论
为什么被折叠?



