StringUtils的isEmpty和isBlank區別

導語

org.apache.commons.lang3 提供了String常用的操作,在日常的開發中,用到的非常多,常用的有isEmpty(String str)、isBlank(String str); 判斷字符串是否爲空、null、""等。但是這兩個方法的使用是有一定的區別的,本片文章就專門分析一下這兩個方法的不同。

maven依賴

<!--apache commons-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>

StringUtils.isEmpty()方法

StringUtils.isEmpty(str) 判斷字符串內容是否爲空,爲空標準是str==null || str.length()==0,包括null、""。

看下面的例子做具體的分析:

System.out.println(StringUtils.isEmpty(null));   結果 true
    
System.out.println(StringUtils.isEmpty(""));     結果true

System.out.println(StringUtils.isEmpty("  "));   結果false

System.out.println(StringUtils.isEmpty("aaa"));  結果false 

StringUtils.isNotEmpty(str) 等價於!str.isEmpty(str) 表示非空。

StringUtils.isBlank()方法

StringUtils.isBlank(str)判斷字符串內容爲空,內容爲空包括 null、""、" "。

看下面的例子做具體的分析:

System.out.println(StringUtils.isBlank(null));  結果是true

System.out.println(StringUtils.isBlank(""));    結果是true

System.out.println(StringUtils.isBlank("  "));  結果是true

System.out.println(StringUtils.isBlank("aaa")); 結果是false

總結

通過上面的比較可以看出:

  1. isEmpty 沒有忽略空格參數,是以是否爲空和是否存在爲判斷依據。
  2. isBlank 是在 isEmpty 的基礎上進行了爲空(字符串都爲空格、製表符、tab 的情況)的判斷。(一般更爲常用)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章