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 中的字符串标记?
最佳答案
使用字符串
您可以使用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
关于java - java中的文本格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43192793/