本文将针对 Sprting 和 commons-lang3 的 SpringUtils 工具库中如何判断字符串是否为空字符串,即字符串为 null、 长度为 0 或者全部是空格。
/**
* Check whether the given {@code String} contains actual <em>text</em>.
* <p>More specifically, this method returns {@code true} if the
* {@code String} is not {@code null}, its length is greater than 0,
* and it contains at least one non-whitespace character.
* @param str the {@code String} to check (may be {@code null})
* @return {@code true} if the {@code String} is not {@code null}, its
* length is greater than 0, and it does not contain whitespace only
* @see #hasText(CharSequence)
*/
public static boolean hasText(String str) {
// 在正式判断是否为空串前,先判断是否为 null 或长度 < 0,
// 可避免空指针和 containsText() 函数调用
return (hasLength(str) && containsText(str));
}
private static boolean containsText(CharSequence str) {
int strLen = str.length();
for (int i = 0; i < strLen; i++) {
// 不是空白字符就直接返回,后续字符不需要在判断
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}/**
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is
* not empty and not null and not whitespace only
* @since 2.0
* @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
*/
public static boolean isNotBlank(final CharSequence cs) {
// 与 Spring 的代码比较,多做了一次取反
return !isBlank(cs);
}
/**
* <p>Checks if a CharSequence is empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</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 only
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(final CharSequence cs) {
int strLen;
// 这里将 cs.length() 写在 cs == null 后面同样可以
// 避免空指针,并且在为空的情况下少调用一次 cs.length() 方法
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
// 不是空白字符就直接返回,后续字符不需要在判断
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}