1. 程式人生 > 其它 >isEmpty 和 isBlank 的用法區別

isEmpty 和 isBlank 的用法區別

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

StringUtils.isEmpty()

是否為空. 可以看到 " " 空格是會繞過這種空判斷,因為是一個空格,並不是嚴格的空值,會導致isEmpty(" ")=false

StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true StringUtils.isEmpty(" ") = false StringUtils.isEmpty(“bob”) = false StringUtils.isEmpty(" bob ") = false
public static boolean isEmpty(final CharSequence cs) {
    return cs == null || cs.length() == 0;
}

StringUtils.isNotEmpty()

相當於不為空 ,= !isEmpty()

public static boolean
isNotEmpty(final CharSequence cs) { return !isEmpty(cs); }

StringUtils.isAnyEmpty()

是否有一個為空,只有一個為空,就為true.

StringUtils.isAnyEmpty(null) = true
StringUtils.isAnyEmpty(null, “foo”) = true
StringUtils.isAnyEmpty("", “bar”) = true
StringUtils.isAnyEmpty(“bob”, “”) = true
StringUtils.isAnyEmpty(
" bob ", null) = true StringUtils.isAnyEmpty(" ", “bar”) = false StringUtils.isAnyEmpty(“foo”, “bar”) = false
/**
 * @param css  the CharSequences to check, may be null or empty
 * @return {@code true} if any of the CharSequences are empty or null
 * @since 3.2
 */
public static boolean isAnyEmpty(final CharSequence... css) {
  if (ArrayUtils.isEmpty(css)) {
    return true;
  }
  for (final CharSequence cs : css){
    if (isEmpty(cs)) {
      return true;
    }
  }
  return false;
}

StringUtils.isNoneEmpty()

相當於!isAnyEmpty(css), 必須所有的值都不為空才返回true

/**
 * <p>Checks if none of the CharSequences are empty ("") or null.</p>
 *
 * <pre>
 * StringUtils.isNoneEmpty(null)             = false
 * StringUtils.isNoneEmpty(null, "foo")      = false
 * StringUtils.isNoneEmpty("", "bar")        = false
 * StringUtils.isNoneEmpty("bob", "")        = false
 * StringUtils.isNoneEmpty("  bob  ", null)  = false
 * StringUtils.isNoneEmpty(" ", "bar")       = true
 * StringUtils.isNoneEmpty("foo", "bar")     = true
 * </pre>
 *
 * @param css  the CharSequences to check, may be null or empty
 * @return {@code true} if none of the CharSequences are empty or null
 * @since 3.2
 */
public static boolean isNoneEmpty(final CharSequence... css) {

https://mp.weixin.qq.com/s/hlSQbTRRzLNZvr_eu_lT_g

故鄉明