Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-06-04) 阅读数 11 #程序编程
文章标签 Java

在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或更高版本,建议使用该方法来判断字符串是否为空。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门