Swap characters of string in C#

王林
Release: 2023-09-06 18:01:06
forward
1013 people have browsed it

C# 中交换字符串的字符

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

First, let's say our string is -

string str = "PQRQP";
Copy after login

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();
Copy after login

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);
   }
}
Copy after login

Output

QPRPQ
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!