0

I want to replace all 'A' of a string by 'B', and all 'B' by 'Z' so that the result of "ABCAAB" will be "BZCBBZ".

Is there a way to replace the following code using the replaceAll function?

String init = "ABCAAB"
String res = "";

for (char c: init.toCharArray()){
    switch (c) {
        case 'A':res = res+'B';
        case 'B':res = res+'Z';

        default :res = res+c;

       }
    }
Kzryzstof
  • 7,688
  • 10
  • 61
  • 108
jtobelem
  • 749
  • 2
  • 6
  • 23
  • 1
    `String res = init.replaceAll("B", "Z").replaceAll("A", "B");` – anubhava Sep 18 '18 at 09:59
  • Simpler: `String res = init.replace("B", "Z").replace("A", "B");` – Wiktor Stribiżew Sep 18 '18 at 10:01
  • tricky! but is there possible doing it once (if I had more replacements to do and no order possible to perform them) – jtobelem Sep 18 '18 at 10:01
  • @WiktorStribiżew I don't think your duplicate is correct, that question is about replacing words in a string, this one is about replacing letters where the replacement of one letter could also be a letter that if it wasn't a replacement character would be being replaced by a third character. – JGNI Sep 18 '18 at 10:07
  • @JGNI This is surely a dupe. If you help me find a better dupe, I will change the dupe link. Just found [this one](https://stackoverflow.com/questions/43719805/replace-multiple-characters-in-string-with-multiple-different-characters). And [this one](https://stackoverflow.com/questions/5470630/what-is-an-efficient-way-to-replace-many-characters-in-a-string). – Wiktor Stribiżew Sep 18 '18 at 10:09
  • 1
    @WiktorStribiżew I may be showing my lack of coffee this morning but I don't see how either solve the a => b, b => c mapping without converting ab to cc. Note that the OP says he could have the following mapping a => b, b => c, c => a which means there is no correct way of ordering replacements. – JGNI Sep 18 '18 at 10:21

1 Answers1

1

If you know that your string is in upper case letters then you can make the replacement characters lower case, thus marking them as changed. This means that you can change A to b and B to z with out changing A to Z. Once all the transformations have been done you can upper case the string.

JGNI
  • 3,933
  • 11
  • 21