如何将字符串中的每个字母与映射的键进行比较? 如果每个字母都作为 map 的键存在,请将其更改为大写字母。
String str = "abcdef";
Map<String, String> map = new HashMap<String, String>();
map.put("a", "A");
map.put("b", "B");
map.put("c", "C");
map.put("d", "D");
map.put("e", "E");
结果应为“ABCDEf”
。
如果字符串中的字母在映射中不存在,则该字母将保留在原处。
最佳答案
你可以做
String after = Stream.of(str.split("")) // a stream of a String for each letter
.map(c-> map.getOrDefault(c, c)) // look up replacement or leave
.collect(Collectors.joining("")); //join into string with no separator
How do I use String#toCharArray() and String.ValueOf(char[] data)
您可以使用循环来代替。
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length;i ++)
chars[i] = map.getOrDefault(""+chars[i], ""+chars[i]).charAt(0);
String after = new String(chars);
关于java - 字符串和映射比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42269747/