想知道是否可以在 String.format() 中组合单个字符串和可变参数字符串,如下所示:
String strFormat(String template, String str, String... moreStrs) {
return String.format(template, str, moreStrs);
}
如果我这样调用上面的代码:
strFormat("%s/%s/%s", "hello", "world", "goodbye");
我得到 java.util.MissingFormatArgumentException:格式说明符 's'
这个有效:
String strFormat(String template, String... moreStrs) {
return String.format(template, moreStrs);
}
以及这个作品:
String strFormat(String template, String str1, String str2) {
return String.format(template, str1, str2);
}
是否有可能让它发挥作用?
String strFormat(String template, String str, String... moreStrs) {
return String.format(template, str, moreStrs);
}
谢谢!
最佳答案
你可以这样做:
String strFormat(String template, String str, String... moreStrs)
{
String[] args = new String[moreStrs.length + 1];
// fill the array 'args'
System.arraycopy(moreStrs, 0, args, 0, moreStrs.length);
args[moreStrs.length] = str;
return String.format(template, args);
}
关于java - 在 String.format() 中组合使用 String 和 Varargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17935596/