字符串工具-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);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM