java怎么判断字符串是否为空
在Java中,可以使用以下方法来判断字符串是否为空:
- 使用
length()
方法,判断字符串的长度是否为0:
String str = "example";
if (str.length() == 0) {
System.out.println("字符串为空");
} else {
System.out.println("字符串不为空");
}
- 使用
isEmpty()
方法,判断字符串是否为空字符串(长度为0):
String str = "example";
if (str.isEmpty()) {
System.out.println("字符串为空");
} else {
System.out.println("字符串不为空");
}
- 使用
isBlank()
方法,判断字符串是否为空或只包含空格:
String str = "example";
if (str.isBlank()) {
System.out.println("字符串为空");
} else {
System.out.println("字符串不为空");
}
其中,isBlank()
方法是在Java 11中引入的,如果使用的是Java 11或更高版本,建议使用该方法来判断字符串是否为空。
版权声明
本文仅代表作者观点,不代表米安网络立场。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。