Graham
Graham

Reputation: 809

How to swap characters in a string

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?

Upvotes: 9

Views: 27303

Answers (7)

Graham
Graham

Reputation: 809

I ended up with this extension method:

string Swap( this string s, char a, char b, char unused)
{
    return s.Replace( a, unused).Replace( b, a).Replace( unused, b);
}

Then I changed it to:

string Swap( this string s, char a, char b)
{
    return new string( s.Select( ch => (ch == a) ? b :(ch == b) ? a : ch).ToArray());
}

Upvotes: 2

Nikolay Kostov
Nikolay Kostov

Reputation: 16983

Iterate through the characters of s and if you find A put B (and vice-versa).

StringBuilder newString = new StringBuilder(s.Length);
foreach(var ch in s)
{
    if (ch == 'A') newString.Append('B');
    else if (ch == 'B') newString.Append('A');
    else newString.Append(ch);
}

s = newString.ToString();

Upvotes: 2

ocuenca
ocuenca

Reputation: 39386

A solution to your problem could be this:

 string s = "AABB";
 var dict = new Dictionary<char, char> {{'A', 'B'}, {'B', 'A'}};

 s = new string(s.Select(c => dict.ContainsKey(c) ? dict[c] : c).ToArray());

This way you can replace all the characters that you want, just add the key/value pair to the dictionary

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

Copying the string into StringBuilder and doing replacements character-by-character is one way of achieving 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 wish to use Replace, and there is a character that is guaranteed to be absent from your string, you could do it in the same way that you do swaps with a temporary variable:

s= s.Replace( 'A', '~').Replace( 'B', 'A').Replace( '~', 'B');

The above assumes that ~ is not present in the original string.

Upvotes: 3

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

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

Upvotes: 6

James Thorpe
James Thorpe

Reputation: 32222

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

Upvotes: 6

Adil Mammadov
Adil Mammadov

Reputation: 8706

You can try this:

string s = "ABABAB";
char placeholder = '~';

//After this s is BABABA
s = s.Replace('A', placeholder).Replace('B', 'A').Replace(placeholder, 'B');

Upvotes: 2

Related Questions