StringUtils工具类的isBlank()方法使用说明

在校验一个String类型的变量是否为空时,通常存在3中情况

  1.  是否为 null
  2. 是否为 ""
  3. 是否为空字符串(引号中间有空格)  如: "     "。

StringUtils的isBlank()方法可以一次性校验这三种情况,返回值都是true

下边是StringUtils的源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
  * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
  *
  * <pre>
  * StringUtils.isBlank(null)      = true
  * StringUtils.isBlank("")        = true
  * StringUtils.isBlank(" ")       = true
  * StringUtils.isBlank("bob")     = false
  * StringUtils.isBlank("  bob  ") = false
  * </pre>
  *
  * @param cs  the CharSequence to check, may be null
  * @return {@code true} if the CharSequence is null, empty or whitespace
  * @since 2.0
  * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
  */
public  static  boolean isBlank(final CharSequence cs) {
     int  strLen;
     if  (cs ==  null  || (strLen = cs.length()) == 0) {
         return  true ;
     }
     for  ( int  i = 0; i < strLen; i++) {
         if  (Character.isWhitespace(cs.charAt(i)) ==  false ) {
             return  false ;
         }
     }
     return  true ;
}

 从注释我们可以看到,当受检查的值时 null 时,返回true,当受检查值时 ""时,返回值时true,当受检查值是空字符串时,返回值是true。

【转载】:https://www.cnblogs.com/snn0605/p/6387816.html

  1.  是否为 null
  2. 是否为 ""
  3. 是否为空字符串(引号中间有空格)  如: "     "。

StringUtils的isBlank()方法可以一次性校验这三种情况,返回值都是true

下边是StringUtils的源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
  * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
  *
  * <pre>
  * StringUtils.isBlank(null)      = true
  * StringUtils.isBlank("")        = true
  * StringUtils.isBlank(" ")       = true
  * StringUtils.isBlank("bob")     = false
  * StringUtils.isBlank("  bob  ") = false
  * </pre>
  *
  * @param cs  the CharSequence to check, may be null
  * @return {@code true} if the CharSequence is null, empty or whitespace
  * @since 2.0
  * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
  */
public  static  boolean isBlank(final CharSequence cs) {
     int  strLen;
     if  (cs ==  null  || (strLen = cs.length()) == 0) {
         return  true ;
     }
     for  ( int  i = 0; i < strLen; i++) {
         if  (Character.isWhitespace(cs.charAt(i)) ==  false ) {
             return  false ;
         }
     }
     return  true ;
}

 从注释我们可以看到,当受检查的值时 null 时,返回true,当受检查值时 ""时,返回值时true,当受检查值是空字符串时,返回值是true。

【转载】:https://www.cnblogs.com/snn0605/p/6387816.html

猜你喜欢

转载自www.cnblogs.com/xianfengzhike/p/9417330.html