我正在尝试替换输入字符串中的特殊字符。我创建了一个HashMap,将所有特殊字符作为键,并将值替换为它们。如何在不遍历整个Map的情况下替换输入字符串中的特殊字符。请注意,这张地图的尺寸可能会增加。
String input= "This is xx and yy for reference"
private static HashMap<String,String> MyHashMap;
static {
MyHashMap = new HashMap<>();
MyHashMap.put("xx", " x");
MyHashMap.put("yy", " y");
MyHashMap.put("zz", " z");
}
// I am looping over the entire collection, which I would like to avoid.
for (Map.Entry<String, String> entry : MyHashMap.entrySet()) {
input = input.toString().replaceAll(entry.getKey(), entry.getValue());
}
Expected output: This is x and y for reference.
代码已执行,但我正在尝试寻找更好的解决方案