我得到一个字符串模板和一个可变长度参数列表。我需要 我需要将参数插入模板并发送结果。
例如:
模板:“%1s 测试 %2s 测试 %1s”
参数:“猫”,“狗”
结果:“CAT 测试 DOG 测试 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作为第二个参数 varargs,所以你可以像这样重写你的代码:
public static String getStringFromTemplate(String template, String ...args) {
return String.format(template, args);
}
此外,如果您想多次使用一个参数,您应该更改模板字符串:
template = "%1$s test %2$s test %1$s";
您可以找到易于理解的教程 here .
关于java - 对 String.format() 使用可变长度参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60339427/