I need to replace several substrings in a string
Let's say:
- replace all A in original string to B
- replace all B in original string to D
so for example "AB gives BD"
The "naive" approach doesn't work properly:
string S="AB";
S=S.Replace("A","B");
S=S.Replace("B","D");
as it will give DD instead of BD. (first A is changed to B but then is unnecessarily changed to D)
How to deal with such cases? Does it make sense with substrings of any size to do such a separate replacements?
EDIT: I gave some not real life example where in fact it would work doing it in reverse order(first B to D, then A to B) But as others noticed I'm interested in more general solutions: for any list of char substitutions and for any list of words substitutions
With chars I suppose now a good approach is just to go through all chars in a string and build a new string making replacements when necessary.
For words I suppose it could be more difficult, what if one replaced word is a part of another word?
For example
string S="man superman woman superwoman"
and I want replace "man" to "boy" and "woman" to "girl" only as single words