C# String Replace Method

In c#, the string Replace method is used to replace a specified string or a character in all occurrence of the given string.

 

The replace method will return a new string after replacing all occurrences of a specified string or a character.

 

Following is the pictorial representation of the replace method in c# programming language.

 

C# String Replace Method Representation Diagram

 

If you observe the above diagram, we are replacing the “Hi” word in a given string “Hi Guest Hi” with “Welcome” using the Replace method. Once the replacement is done, then the Replace method will return a new string like “Welcome Guest Welcome”.

C# String Replace Method Syntax

Following is the syntax of defining a Replace method to replace a particular part of a string or a character in c# programming language.

 

public string Replace(char oldchar, char newchar) 

public string Replace(string oldstring, string newstring)

If you observe syntax, the Replace method will replace all occurrences of oldchar / oldstring with newchar / newstring in a given string and return it as a new string.

C# String Replace Method Example

Following is the example of using the Replace() method to replace a particular part of a string or a character c# programming language.

 

using System;

 

namespace Tutlane

{

    class Program

    {

        static void Main(string[] args)

        {

            string msg = "Hi Guest Hi";

            string nmsg = msg.Replace("Hi", "Welcome");

            Console.WriteLine("Old: {0}", msg);

            Console.WriteLine("New: {0}", nmsg);

 

            string x = "aaaaa";

            string nx = x.Replace("a", "b").Replace("b", "c");

            Console.WriteLine("Old: {0}", x);

            Console.WriteLine("New: {0}", nx);

 

            string y = "1 2 3 4 5 6 7";

            string ny = y.Replace(" ", ",");

            Console.WriteLine("Old: {0}", y);

            Console.WriteLine("New: {0}", ny);

 

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we used a Replace() method to replace particular part of string or a character in given string and returning a new string.

 

When you execute the above c# program, you will get the result as shown below.

 

C# String Replace Method Example Result

 

This is how we can use Replace() method to replace a particular part of a string or a character in c# programming language.

Topics Covered