How To Replace Characters In A C# String

Introduction

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.

Method Description
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.

// Replace a char  
string odd = "1, 3, 5, 7, 9, 11, 13, 15, 17, 19";  
Console.WriteLine($"Original odd: {odd}");  
string newOdd = odd.Replace(',', ':');  
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.

string authors = "Mahesh Beniwal, Neel Beniwal, Raj Beniwal, Dinesh Beniwal";  
Console.WriteLine($"Authors with last names: {authors}");  
// Remove all Beniwal with space and remove space with empty string  
string firstNames = authors.Replace(" Beniwal", "");  
Console.WriteLine($"Authors without last names: {firstNames}");  

The complete program is listed in Listing 1. 

using System;  
namespace ReplaceStringSample {  
    class Program {  
        static void Main(string[] args) {  
            /** Replace sample **/  
            // Replace a char    
            string odd = "1, 3, 5, 7, 9, 11, 13, 15, 17, 19";  
            Console.WriteLine($ "Original odd: {odd}");  
            string newOdd = odd.Replace(',', ':');  
            Console.WriteLine($ "New Odd: {newOdd}");  
            string authors = "Mahesh Beniwal, Neel Beniwal, Raj Beniwal, Dinesh Beniwal";  
            Console.WriteLine($ "Authors with last names: {authors}");  
            // Remove all Beniwal with space and remove space with empty string    
            string firstNames = authors.Replace(" Beniwal", "");  
            Console.WriteLine($ "Authors without last names: {firstNames}");  
            Console.ReadKey();  
        }  
    }  
}  

Listing 1.

The output of Listing 1 looks like Figure 1.

Figure 1.

Here is a detailed tutorial: Strings in C#


Similar Articles
Mindcracker
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.