
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swapping Characters of a String in C#
To swap characters of a string, use the Select method.
Firstly, 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();
The above replaces the characters.
Let us see the compelet code −
Example
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
Advertisements