CreativiTimothy
CreativiTimothy

Reputation: 127

Replace multiple characters with multiple replacements in a String in Java?

I need to replace multiple characters with multiple replacements in a String. I want to replace the following letters:

Z, I, K, A, Y, W, X, F, S, Q, V, G, N, O, H, J, B, P, T, R, M, E, L, C, U, D

with the corresponding:

E, T, O, A, I, N, R, S, H, L, D, F, M, C, U, G, W, Y, B, P, V, K, J, Q, Z, X

For example, 'Z' becomes 'E', 'I' becomes 'T', etc. Here's some example code:

public static void main(String[] args) {
    String s = "LAMA XZRQAOZ";
    // Replacing code
    // Output: s = "JAVA REPLACE"
}

What is the simplest way to do this?

Note: I have tried using an array along with a for loop, but that replaces the letter more than once, so it replaces it into the wrong letter.

Note2: The String I'm actually trying to do is over 10000 characters long, so I don't know if iterating 1 character at a time will be too slow in performance.

Upvotes: 0

Views: 2135

Answers (1)

Stephen C
Stephen C

Reputation: 718678

The simplest way is to load the String into a StringBuilder and then iterate through the StringBuilder, testing and replacing the characters one at a time. Pick the replacement characters either in a switch statement, or by using a Map lookup.

(A Map lookup is simpler / less code. A switch statement should be faster.)

See @Daniel Nugent's answer for an example solution ...


I suspect that your failed attempt was like this:

  for (replacement : ...) {
     str = str.replaceAll(...);
  }

Obviously, that doesn't work because the replaced characters are then potentially subjected to the next round of replacement.

In fact, it is not practical to implement this form of replacement using any of the existing String.replace... methods.


Note2: The String I'm actually trying to do is over 10000 characters long, so I don't know if iterating 1 character at a time will be too slow in performance.

It won't be. In fact it will be orders of magnitude faster than multiple calls to replace, because the replace calls also have to iterate over the string one character at a time behind the scenes. Indeed, it is impossible to do replacements of individual characters in a String without stepping through each character position.

Upvotes: 2

Related Questions