Hutool StrUtil 教程

StrUtil 是 Hutool 工具库中处理字符串的核心工具类,提供了大量静态方法,弥补了 Java 原生字符串处理的不足。

Maven 依赖

XML 复制代码
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.26</version>
</dependency>

常用方法

1. 判空方法

java 复制代码
// 判断是否为 null 或空字符串
StrUtil.isEmpty("");        // true
StrUtil.isEmpty(" ");       // false(空格不是空)
StrUtil.isEmpty(null);      // true

// 判断是否为 null 或空白字符(空格、制表符等)
StrUtil.isBlank(" ");       // true
StrUtil.isBlank("\t\n");    // true
StrUtil.isBlank("abc");     // false

// 非空判断(取反)
StrUtil.isNotEmpty("abc");  // true
StrUtil.isNotBlank("abc");  // true

// 判断是否全部为空
StrUtil.hasEmpty("a", "", "c");     // true
StrUtil.hasBlank("a", " ", "c");    // true

// 判断是否全部非空
StrUtil.isAllNotEmpty("a", "b", "c");  // true

2. 字符串截取

java 复制代码
String str = "abcdefgh";

// 截取指定位置
StrUtil.sub(str, 2, 5);     // "cde"(从索引2到5,不含5)
StrUtil.sub(str, 2, -2);    // "cdef"(负索引从末尾计数)

// 截取前缀/后缀
StrUtil.subPre(str, 3);     // "abc"(前3个字符)
StrUtil.subSuf(str, 3);     // "defgh"(从索引3开始到末尾)
StrUtil.subSufByLength(str, 3);  // "fgh"(最后3个字符)

// 截取指定字符串之前/之后
StrUtil.subBefore("abcde", "cd", false);   // "ab"(首次出现之前)
StrUtil.subAfter("abcde", "cd", false);    // "e"(首次出现之后)
StrUtil.subBetween("abccd", "b", "d");     // "cc"(两个字符串之间)

3. 字符串格式化

java 复制代码
// 格式化模板(占位符用 {})
StrUtil.format("{} + {} = {}", 1, 2, 3);   // "1 + 2 = 3"

// 带索引的占位符
StrUtil.format("{1} + {2} = {0}", 3, 1, 2); // "1 + 2 = 3"

// 格式化金额
StrUtil.format("#,###,###.##", 1234567.89); // "1,234,567.89"

4. 字符串填充

java 复制代码
// 左填充
StrUtil.fillBefore("abc", '0', 5);   // "00abc"

// 右填充
StrUtil.fillAfter("abc", '0', 5);    // "abc00"

// 居中填充
StrUtil.fillCenter("abc", '0', 5);   // "0abc0"
StrUtil.fillCenter("abc", '0', 6);   // "0abc00"

5. 字符串缩写

java 复制代码
// 缩略字符串(超出部分用...代替)
StrUtil.str("这是一段很长的文本", 5);  // "这是一段很..."
StrUtil.str("短文本", 10);             // "短文本"

// 自定义缩略符
StrUtil.str("这是一段很长的文本", 5, "...");  // "这是一段很..."

6. 移除前缀/后缀

java 复制代码
StrUtil.removePrefix("www.example.com", "www.");    // "example.com"
StrUtil.removeSuffix("example.jpg", ".jpg");        // "example"
StrUtil.removePrefixIgnoreCase("WWW.example.com", "www."); // "example.com"

// 移除所有匹配项
StrUtil.strip("abcabc", "ab");  // "cabc"(只移除第一个匹配)

7. 字符串转换

java 复制代码
// 驼峰转下划线
StrUtil.toUnderlineCase("helloWorld");     // "hello_world"

// 下划线转驼峰
StrUtil.toCamelCase("hello_world");        // "helloWorld"

// 首字母大写
StrUtil.upperFirst("hello");               // "Hello"

// 首字母小写
StrUtil.lowerFirst("Hello");               // "hello"

// 全角转半角
StrUtil.toHalfWidth("123");              // "123"

// 半角转全角
StrUtil.toFullWidth("123");                // "123"

8. 字符串掩码

java 复制代码
String str = "ababa";

// 查找字符位置
StrUtil.indexOf(str, 'b');           // 1(首次出现)
StrUtil.lastIndexOf(str, 'b');       // 3(最后出现)

// 替换
StrUtil.replace("abcabc", "ab", "xy");     // "xycxyc"
StrUtil.replaceIgnoreCase("Abc", "ab", "xy"); // "xyc"

// 替换指定位置
StrUtil.replace("abcdef", 2, 4, "**");     // "ab**ef"

9. 查找与替换

java 复制代码
// 隐藏部分字符
StrUtil.hide("13812345678", 3, 7);     // "138****5678"
StrUtil.hide("张三丰", 1, 2);           // "张*丰"

// 自定义掩码字符
StrUtil.hide("13812345678", 3, 7, '#'); // "138####5678"

10. 字符串比较

java 复制代码
// 是否为空或null
StrUtil.isEmpty(null);   // true

// 是否相等(支持null)
StrUtil.equals("abc", "abc");        // true
StrUtil.equalsIgnoreCase("abc", "ABC"); // true

// 是否包含(支持null)
StrUtil.contains("abcdef", "cde");   // true
StrUtil.containsIgnoreCase("Abc", "ab"); // true

// 是否以某字符串开头/结尾
StrUtil.startWith("abcdef", "abc");      // true
StrUtil.endWith("abcdef", "def");        // true

11. 拼接与合并

java 复制代码
// 拼接
StrUtil.concat(true, "a", "b", "c");  // "abc"

// 连接(可指定分隔符)
StrUtil.join(",", "a", "b", "c");     // "a,b,c"

// 连接数组
String[] arr = {"a", "b", "c"};
StrUtil.join(",", arr);               // "a,b,c"

// 连接集合
List<String> list = Arrays.asList("a", "b", "c");
StrUtil.join(",", list);              // "a,b,c"

12. 其他实用方法

java 复制代码
// 获取字符串长度(支持null)
StrUtil.length(null);        // 0
StrUtil.length("abc");       // 3

// 重复字符串
StrUtil.repeat("ab", 3);     // "ababab"

// 去除换行符
StrUtil.cleanBlank("a\nb\r\nc");  // "abc"

// 反转字符串
StrUtil.reverse("abc");      // "cba"

// 截取指定编码长度
StrUtil.subByCodePoint("abc", 2);  // "ab"

// 交换大小写
StrUtil.swapCase("Hello");   // "hELLO"

// 统计字符出现次数
StrUtil.count("ababab", 'a'); // 3

完整示例

java 复制代码
import cn.hutool.core.util.StrUtil;

public class StrUtilDemo {
    public static void main(String[] args) {
        // 判空
        System.out.println(StrUtil.isBlank("   "));     // true
        
        // 格式化
        System.out.println(StrUtil.format("姓名:{},年龄:{}", "张三", 25));
        
        // 驼峰转换
        System.out.println(StrUtil.toUnderlineCase("userName"));  // user_name
        
        // 掩码
        System.out.println(StrUtil.hide("13812345678", 3, 7));    // 138****5678
        
        // 连接
        System.out.println(StrUtil.join("-", "2024", "01", "15")); // 2024-01-15
        
        // 缩写
        System.out.println(StrUtil.str("这是一段很长的文本内容", 8)); // 这是一段很...
    }
}

总结

StrUtil 涵盖了日常开发中 90% 的字符串操作需求,建议:

  • 优先使用 isBlank 而非 isEmpty(更符合业务场景)

  • 使用 format 替代字符串拼接,提高可读性

  • 利用 hide 方法处理敏感信息脱敏

相关推荐
92year4 小时前
用Google ADK从零搭一个能调工具的AI Agent:Python实操全过程
python·ai·mcp
woxihuan1234564 小时前
SQL删除数据时存在依赖关系_设置外键级联删除ON DELETE
jvm·数据库·python
Jetev5 小时前
如何确定SQL字段是否为空_使用IS NULL与IS NOT NULL
jvm·数据库·python
蛐蛐蛐5 小时前
昇腾910B4上安装新版本CANN的正确流程
人工智能·python·昇腾
m0_702036535 小时前
mysql如何处理不走索引的OR查询_使用UNION ALL优化重写
jvm·数据库·python
代钦塔拉6 小时前
Qt4 vs Qt5 带参数信号槽的连接方式详解
开发语言·数据库·qt
2401_846339566 小时前
MySQL在云环境如何选择存储类型_SSD与高性能云盘配置建议
jvm·数据库·python
2601_957780846 小时前
Claude 4.6 对阵 GPT-5.4:2026 开发者大模型 API 选型深度解析
人工智能·python·gpt·ai·claude
2601_957780846 小时前
GPT-5.5 深度解析:2026年4月OpenAI旗舰模型的技术跨越与商业决策指南
大数据·人工智能·python·gpt·openai
zhaoyong2227 小时前
SQL如何统计每个用户的首次行为时间_MIN聚合与分组
jvm·数据库·python