OneBite.Dev - Coding blog in a bite size

Remove A Substring From A String In C#

Code snippet for how to Remove A Substring From A String In C# with sample and detail explanation

Removing a substring from a string is one of the key tasks commonly encountered while dealing with text processing in C#. This article will provide a step by step tutorial on how to accomplish it in a simple and easy-to-understand manner.

Code snippet for removing a substring from a string

Here is a simple code snippet for removing a substring from a string in C#:

using System;

class Program
{
    static void Main()
    {
        string originalString = "Hello, welcome to my world.";
        string substringToRemove = "welcome to";

        string resultingString = originalString.Replace(substringToRemove, "");

        Console.WriteLine($"Resulting string: {resultingString}");
    }
}

When this code is run, it will output: Hello, my world.

Code explanation for removing a substring from a string

In the given code snippet, first, we have declared a string variable named originalString holding the value "Hello, welcome to my world.". We are intending to remove "welcome to" from this string.

Next, we have declared a string variable, substringToRemove, that holds the value of the substring we want to remove from the originalString.

Coming to the main portion of this task, we use the Replace method which is an inbuilt method in C#. This method is called with the originalString and is used to replace every occurrence of the substring substringToRemove with an empty string "". It’s worth noting that the Replace method doesn’t change the originalString itself. Instead, it returns a new string where all occurrences of substringToRemove have been replaced by the specified string - in this case, an empty string. The result is assigned to the resultingString variable.

Finally, we use Console.WriteLine to print the resultingString to the console.

And, there you have it! You now know how to remove a specific substring from a string in C#. These basic string operations are key to mastering C# and text processing. Remember, the Replace method is your friend when it comes to removing substrings. Happy coding!

c-sharp