如何在Java中格式化字符串 [英] How to format strings in Java

查看:150
本文介绍了如何在Java中格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原始问题,但我如何格式化这样的字符串:

Primitive question, but how do I format strings like this:


{2}的步骤{1}

"Step {1} of {2}"

通过使用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中的varargs和autoboxing改进,并将上面的内容变成了一个-liner:

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 做得好一点i18nized复数与选择修饰符。要指定在变量为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中格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆