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;

       }
    }
6
  • 1
    String res = init.replaceAll("B", "Z").replaceAll("A", "B"); Commented Sep 18, 2018 at 9:59
  • Simpler: String res = init.replace("B", "Z").replace("A", "B"); Commented Sep 18, 2018 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) Commented Sep 18, 2018 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. Commented Sep 18, 2018 at 10:07
  • 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. Commented Sep 18, 2018 at 10:21

1 Answer 1

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.

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

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.