How to find a replace a word in a string in C#?


Firstly, set the string to be replaced.

string str = "Demo text!";

Now use the replace() method to replace the above string.

string res = str.Replace("Demo ", "New ");

The following is the complete code to replace a word in a string.

Example

 Live Demo

using System;
public class Demo {
   public static void Main() {

      string str = "Demo text!";
      Console.WriteLine(str);

      string res = str.Replace("Demo ", "New ");
      Console.WriteLine("After replacing...");
      Console.WriteLine(res);
   }
}

Output

Demo text!
After replacing...
New text!

Updated on: 22-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements