zoukankan      html  css  js  c++  java
  • 字符串工具-StrUtil(hutool)

    依赖包:

            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.5.7</version>
            </dependency>

    源码举例:

    import cn.hutool.core.util.StrUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.Assert;
    import org.junit.Test;
    
    /**
     * 字符串工具-StrUtil(hutool)
     * 参考文档:https://www.hutool.cn/docs/#/core/%E5%B7%A5%E5%85%B7%E7%B1%BB/%E6%A6%82%E8%BF%B0
     */
    @Slf4j
    public class TestStrUtil {
    
    
        /**
         * 字符串模板
         */
        @Test
        public void testFormat() {
            //通常使用
            String result1 = StrUtil.format("this is {} for {}", "a", "b");
            Assert.assertEquals("this is a for b", result1);
    
            //转义{}
            String result2 = StrUtil.format("this is \{} for {}", "a", "b");
            Assert.assertEquals("this is {} for a", result2);
    
            //转义
            String result3 = StrUtil.format("this is \\{} for {}", "a", "b");
            Assert.assertEquals("this is \a for b", result3);
        }
    
        @Test
        public void testFormat2() {
            String json = "{"id":"{}","typeName":"SQL执行","type":2,"xxlJobId":"{}"}";
            String result1 = StrUtil.format(json, "123", "321");
            log.info(result1);
    
        }
    
        /**
         * 不得不提一下这个方法,有人说String有了subString你还写它干啥,我想说subString方法越界啥的都会报异常,
         * 你还得自己判断,难受死了,我把各种情况判断都加进来了,而且index的位置还支持负数哦,
         * -1表示最后一个字符(这个思想来自于Python,如果学过Python的应该会很喜欢的),
         * 还有就是如果不小心把第一个位置和第二个位置搞反了,也会自动修正(例如想截取第4个和第2个字符之间的部分也是可以的)
         */
        @Test
        public void testSub() {
            String str = "abcdefgh";
            String strSub1 = StrUtil.sub(str, 2, 3); //strSub1 -> c
            String strSub2 = StrUtil.sub(str, 2, -3); //strSub2 -> cde
            String strSub3 = StrUtil.sub(str, 3, 2); //strSub2 -> c
            log.info(strSub1);
            log.info(strSub2);
            log.info(strSub3);
        }
    }
  • 相关阅读:
    2014/11/25 函数
    2014/11/24 条件查询
    2、计算器
    1、winform数据库调用(基本方法)
    1、网页基础
    14、函数输出参数、递归
    13、C#简易版 推箱子游戏
    12、函数
    11、结构体、枚举
    10、特殊集合
  • 原文地址:https://www.cnblogs.com/gongxr/p/14352571.html
Copyright © 2011-2022 走看看