StrUtil 教程
本教程提供了 StrUtil 类的概述,该类是 lightweight-component/aj-util 库的一部分。StrUtil 类为 Java 应用程序中的字符串操作提供了实用工具方法。
简介
StrUtil 提供字符串计数、填充、模板替换、拼接和成员判断等静态方法。
主要特性
- 带占位符的字符串模板
- 字符串填充和格式化
- 使用自定义分隔符连接列表/数组
方法
1. 拼接
join(T[] arr, String str)- 使用分隔符连接数组join(List<String> list, String str)- 使用分隔符连接字符串列表join(List<String> list, String tpl, String str)- 格式化并连接字符串列表
数组和列表重载都将 null 元素输出为空字符串。
3. 模板
simpleTpl(String template, Map<String, Object> params)-${var}替换simpleTpl2(String template, Map<String, Object> data)-#{var}替换simpleTpl(String template, Object data)- JavaBean 属性替换
替换值按字面量处理,值中包含 $ 或 \ 也不会被解释为分组引用。JavaBean 模板会跳过只写属性;
getter 执行失败时,抛出的 RuntimeException 会指出属性名并保留 getter 异常作为 cause。
4. 实用工具
charCount(String str, String _char)- 统计出现次数,支持重叠匹配leftPad(String str, int len, String padding)- 精确填充到len,不会改动原字符串已有空白isWordOneOfThem(String word, String[] arr)- 检查字符串是否在数组中
使用示例
模板
Map<String, Object> values = new HashMap<>();
values.put("name", "John");
String tpl = StrUtil.simpleTpl("Name: ${name}", values);
// "Name: John"
计数与填充
int count = StrUtil.charCount("aaa", "aa"); // 2,重叠匹配也会计数
String padded = StrUtil.leftPad("a b", 6, "$"); // "$$$a b"
连接
String joined = StrUtil.join(Arrays.asList("a", "b", "c"), ","); // "a,b,c"
结论
StrUtil 类提供了全面的实用方法,用于字符串操作,使 Java 应用程序中的常见字符串操作更加方便。