StringUtils里面的 isEmpty方法和isBlank方法的区别

StringUtils里面的 isEmpty方法和isBlank方法的区别

1、isEmpty() 方法

先来看看这个方法的源码:

public static boolean isEmpty(String str) {
		// 判断字符串是否为空或长度为0
        return str == null || str.length() == 0;
}

isEmpty 是判断某个字符串是否为空,判断的标准是

 str == null || str.length() == 0

代码测试:

public class TestStringUtils {
    public static void main(String[] args) {
        System.out.println(StringUtils.isEmpty(null)); // true
        System.out.println(StringUtils.isEmpty("")); // true
        System.out.println(StringUtils.isEmpty(" ")); // false
        System.out.println(StringUtils.isEmpty("\t")); // false
        System.out.println(StringUtils.isEmpty("HelloJava")); // false
        System.out.println(StringUtils.isEmpty(" Hellojava ")); // false
    }
}


2、isBlank()方法

源码:

public static boolean isBlank(String str) {
        int strLen;
        // 判断字符串是否为空或长度为是否为0
        if (str != null && (strLen = str.length()) != 0) {
        // 如果字符串不为空,且长度不为0,进行循环遍历
            for(int i = 0; i < strLen; ++i) {
            // 如果字符串指定位置的值不为空白字符,返回false;否则返回true
                if (!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }
            return true;
        } else {
            return true;
        }
    }
}


isBlank 是判断字符串是否为空或长度为0 或者是由空白符构成


代码测试:

public class TestStringUtils {
    public static void main(String[] args) {
    
        System.out.println(StringUtils.isBlank(null)); // true
        System.out.println(StringUtils.isBlank("")); // true
        System.out.println(StringUtils.isBlank(" ")); // true
        System.out.println(StringUtils.isBlank("\t")); // true
        System.out.println(StringUtils.isBlank("扬帆向海")); // false
        System.out.println(StringUtils.isBlank(" 扬帆向海 ")); // false
    
    }
}

3、总结


isEmpty()方法没有忽略空格,是以是否为空和是否存在为判断依据;

isBlank()方法增加了字符串为空格、制表符的判断。即isBlank()的判断范围更大,它在isEmpty()方法的基础上,包括了空字符的判断。在实际开发中,isBlank()方法更加常用。

 


  • 发表于 2020-02-21 10:25
  • 阅读 ( 1706 )
  • 分类:Java

0 条评论

请先 登录 后评论
不写代码的码农
威猛的小站长

124 篇文章

作家榜 »

  1. 威猛的小站长 124 文章
  2. Jonny 65 文章
  3. 江南烟雨 36 文章
  4. - Nightmare 33 文章
  5. doublechina 31 文章
  6. HJ社区-肖峰 29 文章
  7. 伪摄影 22 文章
  8. Alan 14 文章