【Java】 字符串中{ }占位符替换方面的问题

引入依赖


​​​​​​<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.8</version>
</dependency>

public static void main(String[] args) {

        String name = "张三";
        int age = 16;
        String str1 = "我叫%s,年龄%s";
        String context = String.format(str1, name, age);
        System.out.println("context: " + context);

        System.out.println("-----------------------");

        String st2 = "我叫{0},年龄{1}";
        String context2 = MessageFormat.format(st2, name, age);
        System.out.println("context2: " + context2);

        System.out.println("-----------------------");

        Map<String, String> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", "16");
        //  StrSubstitutor
//        StrSubstitutor strSubstitutor = new StrSubstitutor(map);
        StringSubstitutor strSubstitutor = new StringSubstitutor();
        String str3 = "我叫${name},年龄${age}";
        String context3 = strSubstitutor.replace(str3);
        System.out.println("context3: " + context3);
    }

先来看看StrSubstitutor(已过期)的用法

Map<String,String> valuesMap = new HashMap();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumps over the ${target}.";
 StrSubstitutor sub = new StrSubstitutor(valuesMap);
 String resolvedString = sub.replace(templateString);

org.apache.commons commons-lang3在 3.6以后废弃了该方法,apache建议替换成 commons-text 包中的StringSubstitutor
官方javadoc说明:
https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html

使用StringSubstitutor需要添加apache commons-text依赖

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.8</version>
        </dependency>
使用方法与StrSubstitutor 一样

 Map<String,String> valuesMap = new HashMap();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumped over the ${target}.";
 StringSubstitutor sub = new StringSubstitutor(valuesMap);
 String resolvedString = sub.replace(templateString);
 

参考文章

java字符串占位符替换 - Ethon - 博客园

apache commons-lang3字符串替换方法StrSubstitutor过期_Tino's Space-CSDN博客

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值