Q:

C# program to replace a substring within a specified string

belongs to collection: C# Basic Programs | String programs

0

C# program to replace a substring within a specified string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | String programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to find the occurrence of the specified... >>
<< C# program to get the length of the string...