如何使用参数名称而不是数字来格式化消息?

2022-08-31 15:57:16

我有这样的东西:

String text = "The user {0} has email address {1}."
// params = { "Robert", "myemailaddr@gmail.com" }
String msg = MessageFormat.format(text, params);

这对我来说不是很好,因为有时我的翻译人员不确定{0}和{1}的内容,并且能够重新措辞消息而不必担心参数的顺序也会很好。

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

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

有没有一种简单的方法来做到这一点?

谢谢!抢


答案 1

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

http://www.java2s.com/Code/Java/I18N/AtextformatsimilartoMessageFormatbutusingstringratherthannumerickeys.htm

String text = "The user {name} has email address {email}.";
Map map = new HashMap();
map.put("name", "Robert");
map.put("email", "rhume55@gmail.com");

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

输出:

1st:用户罗伯特有电子邮件地址 rhume55@gmail.com。


答案 2

请参阅StrSubstitutor,从:org.apache.commons.lang3

Map valuesMap = HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);

// resolvedString: "The quick brown fox jumped over the lazy dog."

推荐