写个简单的:
apache commons.lang包的StringUtils经常用来校验或者处理字符串,对比一下isBlank和isEmpty:
System.out.println(StringUtils.isEmpty(null)); // true
System.out.println(StringUtils.isBlank(null)); // true
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isBlank("")); // true
System.out.println(StringUtils.isEmpty(" ")); // false
System.out.println(StringUtils.isBlank(" ")); // true
isEmpty只会判断输入是否为null或者长度为0
isBlank先判断是否为null或者长度为0,是则返回true,否则从第一个字符开始判断,如果该字符不是空格则返回false。
源码如下:
public static boolean isEmpty(String str) { return str == null || str.length() == 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; }