最近自己也经常在项目中使用到了里面的一些方法,在这里将常用的方法总结了一下,方便以后自己查阅。
StringUtils简介
StringUtils是commons-lang3包下面一个实用的字符串处理的工具类。commons-lang3包可以从文档中获得关于其的介绍:"Apache Commons Lang, a package of Java utility classes for the classes that are in java.lang's hierarchy, or are considered to be so standard as to justify existence in java.lang."
从maven仓库的引用数量可以看出该包的流行程度。
image.png
今天主要介绍StringUtils的空检查
空检查(Empty checks)
isEmpty
以前对字符串进行NullPointerException判断和判断空经常使用这样的代码片段:
if (null == str || str.isEmpty()){
doSomeBuiness()
}
现在可使用StringUtils的静态方法:
if (StringUtils.isEmpty()){
doSomeBuiness()
}
StringUtils类isEmpty方法的源码非常简单,通过源码和注释我们就可以明白该方法做了哪些工作:
// Empty checks
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @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;
}
isNotEmpty
看过了,isEmpty方法就很容易明白isNotEmpty方法了。
/**
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
*
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is not empty and not null
* @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
*/
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
isBlank
/**
* <p>Checks if a CharSequence 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 cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace
* @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)) == false) {
return false;
}
}
return true;
}
该方法的作用通过其注释即可得知。isBlank与isEmpty方法的区别是isBlank方法还判断入参字符是不是空白字符。何为空白字符呢?空白字符包括水平制表符,换行、纵向制表符、换页、回车、文件分隔符、组分隔符、记录分隔符、单元分隔符。
网友评论