java字符串占位符替换


添加依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.6</version>
</dependency>
import org.apache.commons.text.StrSubstitutor;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

public class test {

    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 = new StrSubstitutor(map);
        String str3 = "我叫${name},年龄${age}";
        String context3 = strSubstitutor.replace(str3);
        System.out.println("context3: " + context3);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM