How To Replace Characters In A C# String

The String.Replace() method replaces a character or a string with another character or string in a string.
In C#, Strings are immutable. That means the method does not replace characters or strings from a string. The method creates and returns a new string with new characters or strings.
String.Replace() method has two overloaded forms.
Replace(Char, Char)
Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.
Replace(String, String)
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
Example 1
The following example replaces all commas with a colon in a string.
  1. // Replace a char  
  2. string odd = "1, 3, 5, 7, 9, 11, 13, 15, 17, 19";  
  3. Console.WriteLine($"Original odd: {odd}");  
  4. string newOdd = odd.Replace(','':');  
  5. Console.WriteLine($"New Odd: {newOdd}");  
The following example replaces all “ Beniwal” with an empty string so only first names are copied to the new string.
  1. string authors = "Mahesh Beniwal, Neel Beniwal, Raj Beniwal, Dinesh Beniwal";  
  2. Console.WriteLine($"Authors with last names: {authors}");  
  3. // Remove all Beniwal with space and remove space with empty string  
  4. string firstNames = authors.Replace(" Beniwal""");  
  5. Console.WriteLine($"Authors without last names: {firstNames}");  
The complete program is listed in Listing 1. 
  1. using System;  
  2. namespace ReplaceStringSample {  
  3.     class Program {  
  4.         static void Main(string[] args) {  
  5.             /** Replace sample **/  
  6.             // Replace a char    
  7.             string odd = "1, 3, 5, 7, 9, 11, 13, 15, 17, 19";  
  8.             Console.WriteLine($ "Original odd: {odd}");  
  9.             string newOdd = odd.Replace(','':');  
  10.             Console.WriteLine($ "New Odd: {newOdd}");  
  11.             string authors = "Mahesh Beniwal, Neel Beniwal, Raj Beniwal, Dinesh Beniwal";  
  12.             Console.WriteLine($ "Authors with last names: {authors}");  
  13.             // Remove all Beniwal with space and remove space with empty string    
  14.             string firstNames = authors.Replace(" Beniwal""");  
  15.             Console.WriteLine($ "Authors without last names: {firstNames}");  
  16.             Console.ReadKey();  
  17.         }  
  18.     }  
  19. }  
Listing 1.
The output of Listing 1 looks like Figure 1.
Figure 1.
Here is a detailed tutorial: Strings in C#

Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.