引入依赖
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(已过期)的用法
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博客










