Java的String.format是否有其他替代方法可以缓存每次运行时需要格式化解析的格式String insead?它可能看起来像这样
Formatter formatter = new Formatter( "oh %s" );
formatter.format("my"); // oh my
答案 0 :(得分:5)
您可以使用MessageFormat
class。
MessageFormat mf = new MessageFormat("oh {0}");
System.out.println(mf.format(new Object[] {"my"}));
System.out.println(mf.format(new Object[] {"this will do it!"}));
输出:
oh my
oh this will do it!
答案 1 :(得分:5)
您可以查看MessageFormat您可以为模式创建一个实例并使用它:
MessageFormat messageFormat = new MessageFormat(pattern); // initialize once
messageFormat.format(arguments, new StringBuffer(), null).toString(); // use often