Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap characters in a string

Tags:

c#

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?

like image 883
Graham Avatar asked Feb 11 '15 17:02

Graham


2 Answers

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);

Output:

BAZAB

like image 125
Ehsan Sajjad Avatar answered Oct 24 '22 11:10

Ehsan Sajjad


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");
like image 22
James Thorpe Avatar answered Oct 24 '22 09:10

James Thorpe