如何用不同的字符替换字符串中的特定字符? [英] How to replace specific characters in a String with different ones?
本文介绍了如何用不同的字符替换字符串中的特定字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出
String text = "RHKKA";
如何有效地用'H'替换所有'R',用'E'替换所有'H' strong>,所有'K'和'L'以及所有'A'和'O'?
How to efficiently replace all 'R' with 'H', all 'H' with 'E', all 'K' with 'L' and all 'A' with 'O'?
字符串文本应为HELLO
.
推荐答案
您可以创建一个字符映射作为键和值,然后像这样逐个字符地循环遍历:
You can create a Map of Character as key and value, then loop over character by character like so :
String text = "RHKKA";
Map<Character, Character> map = new HashMap<>();
map.put('R', 'H');
map.put('H', 'E');
map.put('K', 'L');
map.put('A', 'O');
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] = map.get(chars[i]);
}
String result = String.valueOf(chars);
System.out.println(result.toString());//HELLO
Java8 +可能的解决方案
或者,如果您使用的是Java8 +,则可以使用:
Java8+ possible solution
Or if you are using Java8+ you can use :
String result = text.chars()
.mapToObj(c -> String.valueOf(map.get((char) c)))
.collect(Collectors.joining());//HELLO
Java9 +可能的解决方案
Java9+ possible solution
Another possible solution if to use Matcher::replaceAll like so :
String text = "RHKKA";
Map<Character, Character> map = Map.of('R', 'H', 'H', 'E', 'K', 'L', 'A', 'O');
text = Pattern.compile(".").matcher(text)
.replaceAll(c -> String.valueOf(map.get(c.group().charAt(0))));//HELLO
您可以阅读有关 Map.of
这篇关于如何用不同的字符替换字符串中的特定字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文