How to change characters in a string

You will tell me that it is easy, I know, but how I change all A to B and all B to A at the same time, s.

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

obviously doesn't quite work, so is this the right way?

+5
source share
7 answers

You can use linq to replace characters:

 string s = "ABZBA"; var result= s.Select(x=> x == 'A' ? 'B' : (x=='B' ? 'A' : x)).ToArray(); s = new String(result); 

Conclusion:

Bazab

+5
source

Use Regex.Replace and MatchEvaluator to complete the task. This will cause strings to be longer than single characters if A and B become more complex:

 s = Regex.Replace(s, "A|B", (m) => m.Value == "A" ? "B" : "A"); 
+4
source

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.

+3
source

Iterate through the characters 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(); 
+2
source

You can try the following:

 string s = "ABABAB"; char placeholder = '~'; //After this s is BABABA s = s.Replace('A', placeholder).Replace('B', 'A').Replace(placeholder, 'B'); 
+2
source

The solution to your problem may be as follows:

  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 you want, just add a key / value pair to the dictionary

+2
source

I got 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()); } 
+2
source

Source: https://habr.com/ru/post/1213155/


All Articles