问题描述
原始问题,但我如何格式化这样的字符串:
Primitive question, but how do I format strings like this:
{2} 的第 {1} 步"
通过使用Java替换变量?在 C# 中很容易.
by substituting variables using Java? In C# it's easy.
推荐答案
除了String.format,也看看java.text.MessageFormat
.格式更简洁,更接近您提供的 C# 示例,您也可以使用它进行解析.
In addition to String.format, also take a look java.text.MessageFormat
. The format less terse and a bit closer to the C# example you've provided and you can use it for parsing as well.
例如:
int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is "{1}", number is {0}.");
System.out.println(fmt.format(args));
一个更好的例子利用了 Java 1.5 中的可变参数和自动装箱改进,并将上面的内容变成了一个单行:
A nicer example takes advantage of the varargs and autoboxing improvements in Java 1.5 and turns the above into a one-liner:
MessageFormat.format("String is "{1}", number is {0}.", 42, "foobar");
MessageFormat
更适合使用选择修饰符进行国际化复数.要指定在变量为 1 时正确使用单数形式的消息,否则可以执行以下操作:
MessageFormat
is a little bit nicer for doing i18nized plurals with the choice modifier. To specify a message that correctly uses the singular form when a variable is 1 and plural otherwise, you can do something like this:
String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });
这篇关于如何在 Java 中格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!