StringUtils 方法的操作对象是 Java.lang.String 类型的对象,是 JDK 提供的 String 类型操作方法的补充,并且是 null 安全的(即如果输入参数 String 为 null 则不会抛出 NullPointerException ,而是做了相应处理,例如,如果输入为 null 则返回也是 null 等)。
除了构造器,StringUtils 中一共有130多个方法,并且都是 static 的,所以我们可以这样调用 StringUtils.xxx()。
常用方法介绍:
字符串是否为空
为空的标准是 str==null 或 str.length()==0
public static boolean isEmpty(String str)
示例:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false //注意在 StringUtils 中空格作非空处理
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
字符串是否非空
等于 !isEmpty(String str)
public static boolean isNotEmpty(String str)
字符串是否为空或长度为0或由空白符
public static boolean isBlank(String str)
public static boolean isNotBlank(String str)
等于 !isBlank(String str)
去掉字符串两端的空字符串
public static String trim(String str)
截取字符串
-
截取第一次出现指定字符之前的字符串
StringUtils.substringBefore(“dskeabcee”, “e”);
结果是:dsk -
截取最后一个出现指定字符之前的字符串
StringUtils.substringBeforeLast(“dskeabcee”, “e”);
结果是:dskeabce -
截取第一次出现指定字符之后的字符串
StringUtils.substringAfter(“dskeabcedeh”, “k”)
结果是:eabcedeh -
截取最后一个出现指定字符之后的字符串
StringUtils.substringAfterLast(“dskeabcedeh”, “e”)
结果是:h -
截取指定位置的字符串
// 注意不包含第三个字符
StringUtils.substring(“dskabcee”, 3);
结果是:abcee// 注意不包含第三个字符,但是包含第五个字符
StringUtils.substring(“dskabcee”, 3, 5);
结果是:ab
获取指定字符串位置
-
获取指定字符或字符串出现的位置,没有出现返回-1
StringUtils.indexOf(“dskeabcedeh”, “eabc”)
结果:3 -
获取指定字符串从 startPos 开始在字符串 str 中第一次出现的位置,没有出现返回-1
StringUtils.indexOf(“dskeabcedeh”, “e”,6)
结果:7