【问题标题】:Text formatting in javajava中的文本格式
【发布时间】:2017-04-03 19:29:32
【问题描述】:
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

public class TestTokenReplacement {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        String message = "this/is/{bad}";
        map.put("bad", "good");
        System.out.println(MessageFormat.format(message, map.get("bad")));
    }
}

预期输出是:this/is/good 如何格式化字符串以替换 Map 中的字符串标记?

【问题讨论】:

标签: java text-formatting


【解决方案1】:

使用字符串

如果你不想像这样导入额外的类,你可以使用String.format()

String message = "this/is/%s";
String.format(message, map.get("bad"));

在这里,您将使用%s 定义要替换的变量。

使用消息格式

您也可以使用MessageFormat 来执行此操作,但您必须使用参数的索引来标识您的变量。即:

Map<String, String> map = new HashMap<>();
String message = "this/is/{0}";
map.put("bad", "good");
System.out.println(MessageFormat.format(message, map.get("bad")));

输出

this/is/good

【讨论】:

  • 我想要替换消息中的字符串标记。
  • @SriniKandula 看看我对 MessageFormat 的回答,它将替换并为您提供预期的输出。您也可以只使用 String.format。
【解决方案2】:
String message = "this/is/{0}";
System.out.println(MessageFormat.format(message, map.get("bad")));

【讨论】:

    【解决方案3】:

    将 {bad} 替换为索引,即 0。如果您查看格式的语法,它是变量参数。每个数字对应于遵循该模式的参数。

        Map<String, String> map = new HashMap<>();
        String message = "this/is/{0}/{1}";
        map.put("bad", "good");
        System.out.println(MessageFormat.format(message, map.get("bad"),"sample"));
    

    另外,如果您想完全按照自己的方式使用它,请尝试使用。 MapFormat.format(文本,地图)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多