是否有使用缓存格式的String.format替代品?

xen*_*ide 5 java formatting

有没有Java的String.format的替代品,它可以缓存每次运行时需要格式解析的格式String insead?它可能看起来像这样

Formatter formatter = new Formatter( "oh %s" );

formatter.format("my"); // oh my
Run Code Online (Sandbox Code Playgroud)

rge*_*man 5

你可以使用这MessageFormat门课.

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!"}));
Run Code Online (Sandbox Code Playgroud)

输出:

oh my
oh this will do it!
Run Code Online (Sandbox Code Playgroud)


Leo*_*ngs 5

您可以查看MessageFormat,您可以为模式创建一个实例并像这样使用它:

MessageFormat messageFormat = new MessageFormat(pattern); // initialize once
messageFormat.format(arguments, new StringBuffer(), null).toString(); // use often
Run Code Online (Sandbox Code Playgroud)