Copying a string into a StringBuilder and executing characters character by character is one way to achieve this:
var s = new StringBuilder(originalString); for (int i = 0 ; i != s.Length ; i++) { var ch = s.Characters[i]; if (ch == 'A') { s.Characters[i] = 'B'; } else if (ch == 'B') { s.Characters[i] = 'A'; } } originalString = s.ToString();
If you want to use Replace , and there is a character that is guaranteed to be missing from your line, you can do it the same way you do swaps with a temporary variable:
s= s.Replace( 'A', '~').Replace( 'B', 'A').Replace( '~', 'B');
The above assumes that ~ not in the source line.
source share