要使用StringUtils类,首先需要导入:import org.apache.commons.lang.StringUtils;这个包
在maven项目中需要添加下面这个依赖:
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
它的常用方法有:
StringUtils.isEmpty(str):
判断字符串是否为"",null
源码:
* @param str the String to check, may be null
* @return <code>true</code> if the String is empty or null
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
代码示例:
String s1="";
String s2=" ";
String s3;
String s4=null;
String s5="曾阿牛"; System.out.println(StringUtils.isEmpty(s1));//s1="";true
System.out.println(StringUtils.isEmpty(s2));//s2=" ";false
//System.out.println(StringUtils.isEmpty(s3));//s3;the local variable s3 may not have been initialized
System.out.println(StringUtils.isEmpty(s4));//s4=null;true
System.out.println(StringUtils.isEmpty(s5));//s5="曾阿牛";false
StringUtils.isBlank(str):
判断字符串是否为""," ",null
源码:
* @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;
}
代码示例:
System.err.println(StringUtils.isBlank(s1));//s1="";true
System.err.println(StringUtils.isBlank(s2));//s2=" ";true
System.err.println(StringUtils.isBlank(s4));//s4=null;true
System.err.println(StringUtils.isBlank(s5));//s5="曾阿牛";false