0
点赞
收藏
分享

微信扫一扫

java中 如何判断字符串为空

扒皮狼 2023-06-27 阅读 56

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

  1. 使用length()方法判断长度是否为0:

String str = "hello";
if (str.length() == 0) {
    System.out.println("字符串为空");
}

  1. 使用isEmpty()方法判断是否为空字符串:

String str = "hello";
if (str.isEmpty()) {
    System.out.println("字符串为空");
}

  1. 使用trim()方法去除字符串前后的空格,然后再判断是否为空:

String str = "   ";
if (str.trim().isEmpty()) {
    System.out.println("字符串为空");
}

以上方法可以用于判断字符串对象是否为空。请注意,如果字符串对象是null,以上方法都会抛出NullPointerException,所以在使用这些方法前,最好先进行null判断。

String str = null;
if (str == null || str.isEmpty()) {
    System.out.println("字符串为空");
}


举报

相关推荐

0 条评论