判断字符串是否为null、是否为空
org.apache.commons.lang3.StringUtils (掌握)
Maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
示例
import org.apache.commons.lang3.StringUtils;
public class DemoTest {
public static void main(String[] args) {
String str = null;
System.out.println(StringUtils.isBlank(str)); //true
System.out.println(StringUtils.isEmpty(str)); //true
str = "";
System.out.println(StringUtils.isBlank(str)); //true
System.out.println(StringUtils.isEmpty(str)); //true
str = " ";
System.out.println(StringUtils.isBlank(str)); //true
System.out.println(StringUtils.isEmpty(str)); //false
}
}
记忆:isBlank()在参数为null、""、" "时,值全部为true
,在实际项目中使用到该方法比较多。
isEmpty 和 isBlank 的区别?
- 英语
empty
英 [ˈempti] 美 [ˈempti]
adj.
空的;空洞的;空虚的;
blank
英 [blæŋk] 美 [blæŋk]
adj.
空白的;空的; isEmpty:判断字符串是否为空字符串,只要有任意一个字符(包括空白字符)就不为空。
其源代码:public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
isBlank:判断字符串是否为空字符串,全部空白字符也为空。
源代码
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs != null && (strLen = cs.length()) != 0) {
for(int i = 0; i < strLen; ++i) {
// 只要有一个字符不为空白字符就返回 false
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
使用技巧
我们要判断一个字符串为空,绝大部分情况下 “空白字符” 也要为空的,严谨来说肯定要用 isBlank
。
org.junit.platform.commons.util.StringUtils (了解)
依赖
org.junit.jupiter
junit-jupiter
5.7.2
test
测试代码
import org.junit.platform.commons.util.StringUtils;
public class DemoTest {public static void main(String[] args) {
String str = null;
System.out.println(StringUtils.isBlank(str)); //true
str = "";
System.out.println(StringUtils.isBlank(str)); //true
str = " ";
System.out.println(StringUtils.isBlank(str)); //true
}
}
源代码
public static boolean isBlank(String str) {
return (str == null || str.trim().isEmpty());
}
还没有评论,来说两句吧...