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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.