gpt4 book ai didi

java - java中的文本格式化

转载 作者:行者123 更新时间:2023-12-01 20:52:01 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com