a=='P'?' Q':(a=='Q'?'P':a)).ToArray();The characters are replaced above. Let's look at the complete code - Example Live Demonstration usingSystem;usingS"/> a=='P'?' Q':(a=='Q'?'P':a)).ToArray();The characters are replaced above. Let's look at the complete code - Example Live Demonstration usingSystem;usingS">

Home  >  Article  >  Backend Development  >  Swap characters of string in C#

Swap characters of string in C#

王林
王林forward
2023-09-06 18:01:061087browse

C# 中交换字符串的字符

To swap the characters of a string, use the Select method.

First, let's say our string is -

string str = "PQRQP";

Now you need to swap every occurrence of P with Q and Q with P -

str.Select(a=> a == 'P' ? 'Q' : (a=='Q' ? 'P' : a)).ToArray();

above Characters replaced.

Let’s see the complete code -

Example

Live Demonstration

using System;
using System.Linq;

public class Program {
   public static void Main() {

      string str = "PQRQP";

      var res= str.Select(a=> a == 'P' ? 'Q' : (a=='Q' ? 'P' : a)).ToArray();
      str = new String(res);

      Console.WriteLine(str);
   }
}

Output

QPRPQ

The above is the detailed content of Swap characters of string in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete