public class StringCheck {
    public static void main(String[] args) {
        // 示例字符串
        String str1 = "";
        String str2 = "  ";
        String str3 = "Hello World";
        // 使用 isEmpty() 方法判断字符串是否为空
        System.out.println("str1 是否为空: " + isEmpty(str1)); // 输出 true
        System.out.println("str2 是否为空: " + isEmpty(str2.trim())); // 输出 true,因为 trim() 去掉了空格
        System.out.println("str3 是否为空: " + isEmpty(str3)); // 输出 false
        // 使用 isBlank() 方法(Java 11 及以上版本)判断字符串是否为空或仅包含空白字符
        System.out.println("str1 是否为空或空白: " + isBlank(str1)); // 输出 true
        System.out.println("str2 是否为空或空白: " + isBlank(str2)); // 输出 true
        System.out.println("str3 是否为空或空白: " + isBlank(str3)); // 输出 false
    }
    // 自定义方法判断字符串是否为空
    public static boolean isEmpty(String str) {
        return str == null || str.isEmpty();
    }
    // 自定义方法判断字符串是否为空或仅包含空白字符(Java 11 及以上版本)
    public static boolean isBlank(String str) {
        return str == null || str.trim().isEmpty();
    }
}isEmpty() 方法:该方法用于检查字符串是否为 null 或者长度为 0。如果是,则返回 true,否则返回 false。isBlank() 方法(Java 11 及以上版本):该方法不仅检查字符串是否为 null 或者长度为 0,还会检查字符串是否仅包含空白字符(如空格、制表符等)。如果是,则返回 true,否则返回 false。trim() 方法:用于去除字符串两端的空白字符。通过这些方法,你可以方便地判断字符串是否为空或仅包含空白字符。
上一篇:java hashmap遍历
下一篇:javacore
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站