find and solve || findandsolve.com
Please wait.....

How to replace a string with another string in C#

In the C# programming language Replace method is used replacing a string with another string is possible. To do this, you use the replace() method to replace the string value. It replaces any occurrence of the given string or character with another one specified.

Replace() method is a string method in C# which method is used to replace all the specified Unicode characters or specified strings from the current string object and returns a new modified string.


Replace String Method Syntax

public string Replace(char oldchar, char newchar)

or

public string Replace(string oldStringValue, string newStringValue)


Parameters

  • oldStringValue:   This is the character data type variable which is you want to remove.
  • newStringValue: This is the character data type variable which is you want to use as a replacement.
  • oldStringValue:   This is the string data type variable which is you want to remove.
  • newStringValue: This is the string data type variable which is you want to use as a replacement. 


Return value

The return value is a new string.


Source Code Example

In the given example, we will demonstrate the use of the replace() method using the c# programming language. You will create a string and replace some strings and characters in it.

using System;
namespace FindAndSolve
{
  public class Program
  {
  /* How to compare two Dates without time in C# */
    public static void Main(string[] args)
    {
  // create string
    string str = "Demo And Solve";
    // replace some characters and strings
    string rep1 = str.Replace("Demo","Find");
    string rep2 = str.Replace(",", "");
    System.Console.WriteLine(rep1);
    System.Console.WriteLine(rep2);
  }
  }
}

Output

Find And Solve

Demo And Solve


In the above code, we first replaced was with "Find". We also replaced, it with whitespace.