4

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.

1
  • 2
    Do you have mappings for an entire alphabet, or just those letters? Commented Aug 26, 2018 at 17:32

4 Answers 4

9

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

Sign up to request clarification or add additional context in comments.

6 Comments

Of course, you need to ensure the mapping is complete (enough), otherwise your output string would be peppered with nulls.
Also perhaps worth pointing out that you don't need the StringBuilder in the first way, you can just update the char[] from toCharArray(), and then build a new string from that. (Or construct the StringBuilder with the entire text, and update it one char at a time. Kinda the same approach.)
@YCF_L yes. And for the second part, I meant that you could do largely the same with StringBuilder result = new StringBuilder(text) and charAt/set, since a StringBuilder is just a wrapper around a char[].
Thank you @AndyTurner good idea I edit my answer with this one
I wish I could upvote twice, for the Java9 Map.of() ;-)
|
0

There is no such function in standard Java but you can look at Apache Commons StringUtils.replaceChars which replaces group with another group in one go, effectively doing the same as Unix tr command:

StringUtils.replaceChars("RHKKA", "RHKA", "HELE") = "HELLO".

Comments

0

I think your best bet is to create a new String or StringBuilder by replacing all characters in the original one with the correct ones.
Something like:

String text = "RHKKA";
StringBuilder newString = new StringBuilder(text.length());

for (int i = 0; i < text.length(); i++) {
     char newChar = text.charAt(i);
     if (text.charAt(i) == 'R')
         newChar = 'H';
     else if (text.charAt(i) == 'H')
         newChar = 'E';
     else if (text.charAt(i) == 'K')
         newChar = 'L';
     else if (text.charAt(i) == 'A')
         newChar = 'O';
     newString.append(newChar);
}
System.out.println(newString); //prints HELLO

Comments

0

Here is an alternative way based on the character replacement:

String text = "RHKKA";

String before = "RHKA";       // before mapping
String after  = "HELO";       // after mapping

String output = Arrays.stream(text.split(""))                   // Split by characters
    .map(i -> String.valueOf(after.charAt(before.indexOf(i))))  // Replace each letter
    .collect(Collectors.joining(""));                           // Collect to String

System.out.println(output);   // HELLO

By the way, I am sure you meant to replace A with O.. not E as you have in the description.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.