Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace specific characters in a String with different ones?

Given a

String text = "RHKKA";

How to efficiently replace all 'R' with 'H', all 'H' with 'E', all 'K' with 'L' and all 'A' with 'O'?

String text would be HELLO then.

like image 887
ilukasschneider Avatar asked Jan 01 '23 22:01

ilukasschneider


1 Answers

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+ 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+ 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

You can read more about Map.of

like image 75
YCF_L Avatar answered Jan 04 '23 12:01

YCF_L