经常使用commons-lang3包中的StringUtils判断 字符串是否为空,isEmpty、isBlank都在使用,但在使用上还有有点小小的区别的。 isEmpty源码// Empty checks //----------------------------------------------------------------------- /** *Checks if a CharSequence is empty ("") or null. * *
* StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false ** *NOTE: This method changed in Lang version 2.0. * It no longer trims the CharSequence. * That functionality is available in isBlank(). * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is empty or null * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) */ public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; } isBlank源码/** *
Checks if a CharSequence is empty (""), null or whitespace only. * *
Whitespace is defined by {@link Character#isWhitespace(char)}. * *
* StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false ** * @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; 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; } 区别for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } isBlank多了一个循环,循环入参中的字符串,若有一个字符不是空,入参字符串不为空,当入参字符串中每个字符都是空格时,isBlank也返回true。 即,针对同一个字符串" "(中间是英文空格),两个方法返回值不一样,isEmpty 返回 false,而 isBlank 则返回 true.