我正在使用Spring和Java 8。
我有一个带参数的字符串,我不知道如何通过参数列表更新参数。
String message = "Today is {0} and {1} is happy";
List<String> params = Arrays.asList("Sunday", "Uri", "Dan");
我想知道我应该使用哪个运算符来获取:
String newMessage = "Today is Sunday and Uri is happy.";
谢谢你
答案 0 :(得分:2)
您可以像这样使用MessageFormat
:
String result = MessageFormat.format(message, params.toArray());
<强>输出
Today is Sunday and Uri is happy
答案 1 :(得分:1)
虽然您已准确回答了您的确切要求。但MessageFormat非常危险且不够灵活,您必须重复更换值。因此,例如,您希望输出字符串为Today is Sunday and Uri is happy. Also, Uri is going to party today.
现在,MessageFormat代码如下所示:
String message = "Today is {0} and {1} is happy. Also, {2} is going to party today.";
List<String> params = Arrays.asList("Sunday", "Uri", "Uri");
String result = MessageFormat.format(message, params.toArray());
这是一个冒险的代码,原因如下:
如果您确实需要某些内容,例如字符串本身中的{test}
或{}
,该怎么办?它会失败。
对于重复值,您必须使用重复的条目管理数组并确保正确的顺序。
如果字符串增长,它实际上是不可读的。
因此,更好的解决方案是使用StrSubstitutor
,如下所示:
String template = "Today is ${day} and ${name} is happy";
Map<String, String> data = new HashMap<>();
data.put("day", "Sunday");
data.put("name", "Uri");
System.out.println(StrSubstitutor.replace(template, data));
请注意,如何替换命名值。这就像在SQL查询中选择?
或named parameters
一样。
StrSubstitutor
来自log4j
框架。
因此,请根据您的需要做出正确的选择。
干杯!