public class StringCheck {
public static void main(String[] args) {
// 定义一个字符串变量
String str = "";
// 方法1: 使用 equals 方法判断是否为空字符串
if (str.equals("")) {
System.out.println("字符串是空的");
} else {
System.out.println("字符串不是空的");
}
// 方法2: 使用 length() 方法判断字符串长度是否为0
if (str.length() == 0) {
System.out.println("字符串是空的");
} else {
System.out.println("字符串不是空的");
}
// 方法3: 使用 isEmpty() 方法判断是否为空字符串 (推荐)
if (str.isEmpty()) {
System.out.println("字符串是空的");
} else {
System.out.println("字符串不是空的");
}
// 方法4: 使用 null 和 trim() 判断是否为 null 或仅包含空白字符
if (str == null || str.trim().isEmpty()) {
System.out.println("字符串是 null 或仅包含空白字符");
} else {
System.out.println("字符串不是 null 且不只包含空白字符");
}
}
}
equals(""):直接比较字符串是否等于空字符串 ""。length() == 0:通过检查字符串的长度是否为 0 来判断是否为空。isEmpty():这是最简洁的方式,专门用于检查字符串是否为空。推荐使用此方法。null 和 trim().isEmpty():不仅检查字符串是否为空,还检查是否为 null 或仅包含空白字符(如空格、制表符等)。上一篇:java mockito
下一篇:java 遍历json
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站