使用参数更新字符串

时间:2018-03-07 20:30:04

标签: java string parameters java-8

我正在使用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.";

谢谢你

2 个答案:

答案 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());

这是一个冒险的代码,原因如下:

  1. 如果您确实需要某些内容,例如字符串本身中的{test}{},该怎么办?它会失败。

  2. 对于重复值,您必须使用重复的条目管理数组并确保正确的顺序。

  3. 如果字符串增长,它实际上是不可读的。

  4. 因此,更好的解决方案是使用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框架。

    因此,请根据您的需要做出正确的选择。

    干杯!

相关问题