Home>

What is the algorithm for replacing two characters in a string?

For example,
Swap A and U for strings like UGCACGAU,
I want to be like AGCUCGUA.

Simply'UGCACGAU'.replaceAll (/ A/g,'U'). replaceAll (/ U/g,'A') naturally doesn't work

What I thought

s = "UGCACGAU"
console.log (s.replace (/ A/g, '@'). replace (/ U/g, 'A'). replace (/ @/g, 'U'))


However, it is not sufficient when considering the case where the character @ is present in the character string.

①Is there any algorithm (or method, etc.) for swapping any two characters without a string like this?

②Is there any algorithm that can be used even if it happens with time difference?

* The time difference is, for example, displaying banana as bbnbnb first, and switching to abnbnb when the user presses the button.

  • Answer # 1

      

    ①Is there any algorithm (or method, etc.) for swapping any two characters without a string like this?

    The hit string is not a simple string, it can be a function feed, so
    The following code will be as intended.

    s = "UGCACGAU";
    replaceMap = {
      A: "U",
      U: "A",
    };
    console.log (s.replace (/ [AU]/g, function (it) {
      return replaceMap [it];
    }));// AGCUCGUA
      

    ②Is there any algorithm that can be used even if it happens with time difference?
      * The time difference is, for example, that banana is displayed as bbnbnb first, and when the user presses the button, it is changed to abnbnb.

    It is possible if you can keep possessing "banana" which is the first character string.

    If you have ingredients and recipes, you can always make the same dish.
    It can be reproduced at any time by managing "what you need at the start" and "work you have done" well, and you can also make it look ahead.

    The following two points are important.
    If you keep studying, you should be able to write freely.

    Where to declare the variable

    What type (string, number, array?) to save the variable

  • Answer # 2

    This method is often used in blacklist + whitelist filters.
    (I'm not a fool, but my parent is OK)

    A common method is to make the middle string a little longer (***, ###, etc.).
    If it is strictly done, it is better to replace after confirming that there is no intermediate string first.
    * If there is, use another string.

      

    ①Is there any algorithm (or method, etc.) for swapping any two characters without a string like this?
      (2) Is there an algorithm that can be used even if it happens due to the time difference?

    I'm not sure about this question, but for reference.