为 String.format() 使用可变长度参数列表

Using a Variable Length Argument List for String.format()

我得到一个字符串模板和一个可变长度参数列表。我需要 我需要在模板中插入参数并发送结果。

例如:

模板:"%1s test %2s test %1s"

参数:"CAT", "DOG"

结果:"CAT test DOG test CAT"

我试过这样做。但是我得到了一个错误,因为事实上,我正在尝试执行字符串 String.format("%1s test %2s test %1s", "value") 这确实是错误的。


    public static void main(String[] args) {
        getStringFromTemplate("%1s test %2s test %1s", "CAT", "DOG");
    }

    public void getStringFromTemplate(String template, String... args){
        ArrayList<String> states = new ArrayList<>();
        Collections.addAll(states, args);
        String s;
        Iterator<String> iter = states.iterator();
        while(iter.hasNext()){
            s = String.format("%1s test %2s test %1s", iter.next());
        }
        rerurn s;
    }

String.format 将可变参数作为第二个参数,因此您可以像这样重写代码:

public static String getStringFromTemplate(String template, String ...args) {
    return String.format(template, args);
}

另外,如果你想多次使用一个参数,你应该改变你的模板字符串:

template = "%1$s test %2$s test %1$s";

你可以找到通俗易懂的教程here

我相信您正在寻找这个:

public String getStringFromTemplate(String template, String... args){
    for (int i=0; i<args.length; i++) {
        String placeholder = "%" + (i+1) + "s";
        String actualValue=args[i];
        template = template.replaceAll(placeholder, actualValue);
    }
    return template;
}

此代码遍历您的参数,从它们在 args 数组中的索引派生一个占位符,并将此占位符的所有出现替换为模板字符串中参数的实际值。

你可以try it here