Java:如何使用 Map<String,String> 填充文本中的占位符?

标签 java string hashmap mapping placeholder

我正在使用一个代码,我想用另一个字符串填充几个字符串占位符。这是我用来测试代码的示例文本。

String myStr = "Media file %s of size %s has been approved"

这就是我填充占位符的方式。由于我希望使用多个占位符,因此我使用了 java Map<>。

Map<String, String> propMap = new HashMap<String,String>();
propMap.put("file name","20mb");
String newNotification = createNotification(propMap);

我使用以下方法来创建字符串。

public String createNotification(Map<String, String> properties){
    String message = ""; 
    message = String.format(myStr, properties);

    return message;
}

如何将两个“%s”替换为“文件名”和“20mb”?

最佳答案

这不是 map 的目的。 您添加的是一个条目“文件名”->“20 mb”,这基本上意味着属性“文件名”的值为“20 mb”。您试图用它做的是“维护一个项目元组”。

请注意,格式化字符串具有固定数量的占位符;您想要一个包含完全相同数量的项目的数据结构;所以本质上是一个数组或List

因此,您想要的是

public String createNotification(String[] properties) {
    assert(properties.length == 2); // you might want to really check this, you will run into problems if it's false
    return String.format("file %s has size %s", properties);
}

如果您想创建 map 中所有项目的通知,您需要执行以下操作:

Map<String,String> yourMap = //...
for (Entry<String,String> e : yourMap) {
    System.out.println(createNotification(e.getKey(), e.getValue()));
}

关于Java:如何使用 Map<String,String> 填充文本中的占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361351/

相关文章:

java - 从 Uri 获取路径

java - runo 主题中的 styles.css 未加载

c++ - 如何有效地使用C++中的字符串数据类型?

java - 使用对象的实例作为 HashMap 键

java - 将单词存储到 Hashmap 中

java - 抽象类和多态性

java - 解决 JUnit 中的重复测试习语

java - 如何在for循环中从字符串中获取最后一个索引

r - 在交替索引上拆分字符串

java - 计算文件中重复的单词