本文介绍了如何使用参数名称而不是数字来格式化消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的东西:

String text = "The user {0} has email address {1}."
// params = { "Robert", "[email protected]" }
String msg = MessageFormat.format(text, params);

这对我来说不是很好,因为有时我的翻译人员不确定 {0} 和 {1} 中的内容,而且能够重新编写消息而不用担心参数的顺序会很好.

This isn't great for me, because sometimes my translators are not sure what goes in the {0} and {1}, also it would be nice to be able to reword the messages without worrying about the order of the args.

我想用可读的名称而不是数字替换参数.像这样:

I'd like to replace the arguments with readable names instead of numbers. Something like this:

String text = "The user {USERNAME} has email address {EMAILADDRESS}."
// Map map = new HashMap( ... [USERNAME="Robert", EMAILADDRESS="[email protected]"]
String msg = MessageFormat.format(text, map);

有没有简单的方法可以做到这一点?

Is there an easy way to do this?

谢谢!抢

推荐答案

您可以为此使用 MapFormat.在此处了解详细信息:

You can use MapFormat for this. Find out the details here:

http://www.java2s.com/Code/Java/I18N/AtextformatssimilartoMessageFormatbutusingstring而不是numerickeys.htm

String text = "The user {name} has email address {email}.";
Map map = new HashMap();
map.put("name", "Robert");
map.put("email", "[email protected]");

System.out.println("1st : " + MapFormat.format(text, map));

输出:

第一:用户 Robert 的电子邮件地址为 [email protected].

这篇关于如何使用参数名称而不是数字来格式化消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:53