打开org.apache.commons.lang包下面的StringUtils.class
/**
* <p>Checks if a String 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 str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
传入一个String类型的参数,返回一个boolean类型
首先判断是否等于null或者长度为0,满足一个就返回true代表空白字符串
如果都不是接着验证
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
str.charAt是根据索引,返回字符,这个索引是从0开始的
String str = "Hello World"; System.out.println(str.charAt(0)); System.out.println(str.charAt(5)); System.out.println(str.charAt(8));执行后输出
H
r
所以这段代码是判断string字符的每个位置是否为空白格,如果是空白格的返回true,不是的返回false,然后做个判断==false,正好相反,只要有一个不是空白格,就返回错误
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
public static boolean isWhitespace(int codePoint) {
return CharacterData.of(codePoint).isWhitespace(codePoint);
}
1.是否等于null或者长度为0,
2.如果都不行就考虑传进来的参数是否都是空白格,就是这种 " ",里面都是空格,
如果都不满足,那这个参数不是blank的
顺便看下StringUtils.isNotBlank的源码,只是调用StringUtils.isBlank加个 !
public static boolean isNotBlank(String str) {
return !StringUtils.isBlank(str);
}