You are going to tell me this is easy, I know, but how do I simultaneously change all A into B, and all B into A, in a string, s.
s= s.Replace( 'A', 'B').Replace( 'B', 'A');
clearly doesn't quite work, so what is the right way?
You can use linq to replace the characters:
string s = "ABZBA";
var result= s.Select(x=> x == 'A' ? 'B' : (x=='B' ? 'A' : x)).ToArray();
s = new String(result);
BAZAB
Use Regex.Replace
and a MatchEvaluator
to do the job. This will cope with strings longer than single characters, if A
and B
ever get more complex:
s = Regex.Replace(s, "A|B", (m) => m.Value == "A" ? "B" : "A");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With