Home »
.Net »
C# Programs
C# program to replace a substring within a specified string
Here, we are going to learn how to replace a substring within a specified string in C#?
Submitted by Nidhi, on October 10, 2020
Here we read a string from the keyboard and then replace the specified substring within the specified string.
Program:
The source code to replace a specified substring within a specified string is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to replace a substring within
//the specified string.
using System;
class Demo
{
static void Main()
{
string str = "Virat is a bad cricketer, he played bad in IPL";
Console.WriteLine("String before replacing substring: \n"+ str);
str = str.Replace("bad", "good");
Console.WriteLine("String after replacing substring: \n" + str);
}
}
Output:
String before replacing substring:
Virat is a bad cricketer, he played bad in IPL
String after replacing substring:
Virat is a good cricketer, he played good in IPL
Press any key to continue . . .
Explanation:
Here, we created a Demo class that contains the Main() method. The Main() method is the entry point of the program. Here we created a string initialized with a sentence.
str = str.Replace("bad", "good");
Using Replace() method, we replaced the substring bad from good within the string str, and then printed the modified string on the console screen.
C# Basic Programs »