C# - Replace a Substring of a String

Given a string, we have to replace a substring from it using C# program?
Submitted by Nidhi, on October 10, 2020 [Last updated : March 21, 2023]

Here we read a string from the keyboard and then replace the specified substring within the specified string.

C# program to replace a substring of a string

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 »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.