【问题标题】:Combined usage of String and Varargs in String.format()String.format() 中 String 和 Varargs 的组合使用
【发布时间】:2013-07-29 22:57:18
【问题描述】:

想知道是否可以在 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: Format specifier '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);
}

谢谢!

【问题讨论】:

  • 为什么要从其余字符串中分离出一个str?您是否尝试要求至少通过一个str
  • 不,API 不是这样定义的。你为什么要这么做?
  • @rgettman 和 Jim Garrison:只是想知道它是否可行,如果不行,想知道解决方法。

标签: java variadic-functions string.format


【解决方案1】:

你可以这样做:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2019-03-05
    相关资源
    最近更新 更多