常用工具类-StringUtils

简介: StringUtils 是 Apache Commons Lang 库中的一个非常有用的工具类,它提供了许多操作 String 的静态方法。

StringUtils常用方法概览

StringUtils 是 Apache Commons Lang 库中的一个非常有用的工具类,它提供了许多操作 String 的静态方法。使用 StringUtils 可以使字符串操作更加简便和高效。以下是一些 StringUtils 中常用的方法:

  1. isEmpty() 和 isNotEmpty():
  • isEmpty(String str): 检查一个字符串是否为空(null 或长度为 0)。
  • isNotEmpty(String str): 检查一个字符串是否不为空。
  1. isBlank() 和 isNotBlank():
  • isBlank(String str): 检查一个字符串是否为空白(null、空或仅包含空白字符)。
  • isNotBlank(String str): 检查一个字符串是否不为空白。
  1. trim() 和 strip():
  • trim(String str): 去除字符串两端的空白字符。
  • strip(String str, String stripChars): 去除字符串两端指定的字符。
  1. equals() 和 equalsIgnoreCase():
  • equals(String str1, String str2): 比较两个字符串是否相等,处理 null 值。
  • equalsIgnoreCase(String str1, String str2): 比较两个字符串是否相等,不区分大小写,同时处理 null 值。
  1. join() 和 split():
  • join(Object[] array, String separator): 使用指定的分隔符将数组元素连接成一个字符串。
  • join(Iterable<?> iterable, String separator): 使用指定的分隔符将可迭代对象的元素连接成一个字符串。
  • split(String str, String separatorChars): 根据指定的分隔符字符集将字符串拆分为数组。
  1. substring() 和 left() / right():
  • substring(String str, int start): 获取字符串从指定位置开始的子字符串。
  • substring(String str, int start, int end): 获取字符串从起始位置到结束位置的子字符串。
  • left(String str, int len): 获取字符串最左边的指定长度的子字符串。
  • right(String str, int len): 获取字符串最右边的指定长度的子字符串。
  1. contains() 和 containsIgnoreCase():
  • contains(String str, CharSequence seq): 检查一个字符串是否包含另一个字符序列。
  • containsIgnoreCase(String str, CharSequence seq): 检查一个字符串是否包含另一个字符序列,不区分大小写。
  1. replace() 和 overlay():
  • replace(String text, String searchString, String replacement): 替换字符串中所有出现的指定子字符串。
  • overlay(String str, String overlay, int start, int end): 用新的字符串覆盖原始字符串的指定部分。
  1. capitalize() 和 uncapitalize():
  • capitalize(String str): 将字符串的首字母变为大写。
  • uncapitalize(String str): 将字符串的首字母变为小写。
  1. remove() 和 delete():
  • remove(String str, char remove): 移除字符串中所有出现的指定字符。
  • deleteWhitespace(String str): 删除字符串中的所有空白字符。

这只是 StringUtils 类提供的方法的一小部分。在实际开发中,这个类可以大大简化字符串的操作和处理。

下面,使用几个StringUtils类的方法练习一下!

① 判断字符串是否为空

常用的判断字符串为空的方法:

  1. isEmpty():检查一个字符串是否为空(null 或长度为 0)。
  2. isBlank(): 检查一个字符串是否为空白(null、空或仅包含空白字符)。
  3. isNotEmpty():检查一个字符串是否不为空。
  4. isNotBlank():检查一个字符串是否不为空白。

查看一下isEmpty()和isBlank()的源码:

// isEmpty
public static boolean isEmpty(CharSequence cs) {
   
    return cs == null || cs.length() == 0;
}
// isBlank
public static boolean isBlank(CharSequence cs) {
   
    int strLen = length(cs);
    if (strLen == 0) {
   
        return true;
    } else {
   
        for(int i = 0; i < strLen; ++i) {
   
            if (!Character.isWhitespace(cs.charAt(i))) {
   
                return false;
            }
        }

        return true;
    }
}

② 分隔字符串

String类的split()方法可以完成字符串切片分割的功能,但是相较于StringUtils类中的split()方法较为不安全,如下面的代码

// 分隔字符串
String strToSplit = null;
String[] split1  = strToSplit.split(strToSplit); // 抛异常 java.lang.NullPointerException

// StringUtils 更为安全,当传入的字符串为空时,不会抛异常
String[] split2 = StringUtils.split(strToSplit);
System.out.println(Arrays.toString(split2)); // null

StringUtils.split()的源码,其实最核心的方法,应该是splitWorker(),splitWorker()方法中完成了字符串切割的字符串检验,字符串切片。

public static String[] split(String str) {
   
    return split(str, (String)null, -1);
}

public static String[] split(String str, String separatorChars, int max) {
   
    return splitWorker(str, separatorChars, max, false);
}

private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) {
   
        if (str == null) {
   
            return null;
        } else {
   
            int len = str.length();
            if (len == 0) {
   
                return ArrayUtils.EMPTY_STRING_ARRAY;
            } else {
   
                List<String> list = new ArrayList();
                int sizePlus1 = 1;
                int i = 0;
                int start = 0;
                boolean match = false;
                boolean lastMatch = false;
                if (separatorChars != null) {
   
                    if (separatorChars.length() != 1) {
   
                        label87:
                        while(true) {
   
                            while(true) {
   
                                if (i >= len) {
   
                                    break label87;
                                }

                                if (separatorChars.indexOf(str.charAt(i)) >= 0) {
   
                                    if (match || preserveAllTokens) {
   
                                        lastMatch = true;
                                        if (sizePlus1++ == max) {
   
                                            i = len;
                                            lastMatch = false;
                                        }

                                        list.add(str.substring(start, i));
                                        match = false;
                                    }

                                    ++i;
                                    start = i;
                                } else {
   
                                    lastMatch = false;
                                    match = true;
                                    ++i;
                                }
                            }
                        }
                    } else {
   
                        char sep = separatorChars.charAt(0);

                        label71:
                        while(true) {
   
                            while(true) {
   
                                if (i >= len) {
   
                                    break label71;
                                }

                                if (str.charAt(i) == sep) {
   
                                    if (match || preserveAllTokens) {
   
                                        lastMatch = true;
                                        if (sizePlus1++ == max) {
   
                                            i = len;
                                            lastMatch = false;
                                        }

                                        list.add(str.substring(start, i));
                                        match = false;
                                    }

                                    ++i;
                                    start = i;
                                } else {
   
                                    lastMatch = false;
                                    match = true;
                                    ++i;
                                }
                            }
                        }
                    }
                } else {
   
                    label103:
                    while(true) {
   
                        while(true) {
   
                            if (i >= len) {
   
                                break label103;
                            }

                            if (Character.isWhitespace(str.charAt(i))) {
   
                                if (match || preserveAllTokens) {
   
                                    lastMatch = true;
                                    if (sizePlus1++ == max) {
   
                                        i = len;
                                        lastMatch = false;
                                    }

                                    list.add(str.substring(start, i));
                                    match = false;
                                }

                                ++i;
                                start = i;
                            } else {
   
                                lastMatch = false;
                                match = true;
                                ++i;
                            }
                        }
                    }
                }

                if (match || preserveAllTokens && lastMatch) {
   
                    list.add(str.substring(start, i));
                }

                return (String[])list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
            }
        }
    }

③ 判断字符串是否为纯数字的字符串

StringUtils.isNumeric()方法,可以更方便的判断当前的字符串是否是一个纯数字的字符串。
StringUtils.isNumericSpace() 方法,可以判断含有空格的数字字符串。

String strNum1 = "123";
String strNum2 = "123.45";
String strNum3 = "123f";
String strNum4 = "123q";
// 判断是否为纯数字字符串
System.out.println(StringUtils.isNumeric(strNum1)); // true
System.out.println(StringUtils.isNumeric(strNum2)); // false
System.out.println(StringUtils.isNumeric(strNum3)); // false
System.out.println(StringUtils.isNumeric(strNum4)); // false


// isNumericSpace() 方法,可以判断含有空格的数字字符串
String strNum5 = "12 3";
System.out.println(StringUtils.isNumericSpace(strNum5)); // true
public static boolean isNumeric(CharSequence cs) {
   
    if (isEmpty(cs)) {
   
        return false;
    } else {
   
        int sz = cs.length();

        for(int i = 0; i < sz; ++i) {
   
            if (!Character.isDigit(cs.charAt(i))) {
   
                return false;
            }
        }

        return true;
    }
}

④ 将集合拼接为字符串

常见的场景,将集合的内容拼接为字符串

// 自己拼接集合内容为字符串
List<String> list = new ArrayList<>();
list.add("zhangsan");
list.add("lisi");
list.add("wangwu");
list.add("zhaoliu");
list.add("houqi");
System.out.println(list.toString()); // [zhangsan, lisi, wangwu, zhaoliu, houqi]

如果我们自己将集合的内容拼接为字符串的话,代码可能会写成下面这样:
写法一:利用增强for遍历集合内容,然后使用String += 去拼接字符串,缺点浪费内存,创建了循环次数+1个String类对象。

String strTemp = null;
for(String item : list){
   
    strTemp +=  item  + ",";
}
System.out.println(strTemp); // nullzhangsan,lisi,wangwu,zhaoliu,houqi,

写法二:使用StringBuilder来完成拼接,还是不够优雅。虽然只创建了两个对象,StringBuilder对象和sb.toString()的一个对象。

StringBuilder sb = new StringBuilder();
for (String item : list){
   
    sb.append(item).append(",");
}
System.out.println(sb);

而利用StringUtils.join()方法,我们可以非常简单的去完成集合内容的拼接,其实这段代码的底层也是StringBuilder,只不过我们调用更为方便了。

String joinListToStr = StringUtils.join(list, ",");
System.out.println(joinListToStr); // zhangsan,lisi,wangwu,zhaoliu,houqi

StringUtils.join()方法底层源码

public static String join(Iterator<?> iterator, String separator) {
   
    if (iterator == null) {
   
        return null;
    } else if (!iterator.hasNext()) {
   
        return "";
    } else {
   
        Object first = iterator.next();
        if (!iterator.hasNext()) {
   
            return Objects.toString(first, "");
        } else {
   
            StringBuilder buf = new StringBuilder(256);
            if (first != null) {
   
                buf.append(first);
            }

            while(iterator.hasNext()) {
   
                if (separator != null) {
   
                    buf.append(separator);
                }

                Object obj = iterator.next();
                if (obj != null) {
   
                    buf.append(obj);
                }
            }

            return buf.toString();
        }
    }
}

小结

StringUtils 是 Apache Commons Lang 库中的一个非常有用的工具类,它提供了许多操作 String 的静态方法。灵活使用,多读源码!

相关文章
|
机器学习/深度学习 JSON 监控
智能定价模型:借助API实时更新商品价格信息
在电子商务的迅猛发展中,价格战成为商家间常见的竞争方式。然而,一成不变的价格策略无法满足市场的即时需求和消费者的多变偏好。因此,智能定价(也称为动态定价)成为了电商平台提升市场竞争力的关键工具。智能定价模型通过实时监控市场数据和消费者行为,自动调整商品价格以最大化收益或实现其他商业目标。本文将深入探讨如何利用API技术实现智能定价,并提供一个Python代码示例来指导读者进行实时价格更新。
|
前端开发
若依(ruoyi)前端Vue3 Element Plus Vite版样式修改
若依(ruoyi)前端Vue3 Element Plus Vite版样式修改
3714 0
|
24天前
|
安全 JavaScript API
2026年阿里云双十一大促·企业级Agent开发实战:基于DeepSeek Harness框架与Cordis内核的构建及部署教程
DeepSeek Harness 代表 Agent 开发范式的根本转变,“一切皆插件”的 Cordis 内核提供极高的自由度,完整的轨迹回放、沙箱安全机制、多模式运行能力,兼顾开发调试、实验评测、生产自动化需求。无论是想要快速搭建代码智能体,还是深度自研一套 Agent 平台,这套框架都提供了可落地的基础设施。 ‌获取完整教程、一键部署入口、API Key 配置、免费 Token 额度领取,请立即访问阿里云百炼大模型服务平台页面,开启你的企业 Agent 开发之旅!
584 1
|
数据采集 监控 大数据
大数据项目管理:从规划到执行的全景指南
大数据项目管理:从规划到执行的全景指南
375 4
|
Java 中间件 调度
SpringBoot整合XXL-JOB【03】- 执行器的使用
本文介绍了如何将调度中心与项目结合,通过配置“执行器”实现定时任务控制。首先新建SpringBoot项目并引入依赖,接着配置xxl-job相关参数,如调度中心地址、执行器名称等。然后通过Java代码将执行器注册为Spring Bean,并声明测试方法使用`@XxlJob`注解。最后,在调度中心配置并启动定时任务,验证任务是否按预期执行。通过这些步骤,读者可以掌握Xxl-Job的基本使用,专注于业务逻辑的编写而无需关心定时器本身的实现。
5845 10
SpringBoot整合XXL-JOB【03】-  执行器的使用
|
SQL JSON 关系型数据库
JSON_TABLE 两全其美
在这篇博客文章中,我将向您展示如何做到这一点,并讨论JSON_TABLE如何启用使用SQL处理JSON数据的新方法。
9689 0
|
SQL 关系型数据库 MySQL
MySQL 更新1000万条数据和DDL执行时间分析
MySQL 更新1000万条数据和DDL执行时间分析
1384 4
|
存储 关系型数据库 MySQL
在 MySQL 中使用 Insert Into Select
【8月更文挑战第11天】
8346 0
在 MySQL 中使用 Insert Into Select