This article illustrates the different techniques to remove or replace a substring from a string in C#.

The standard solution to remove a substring from a string is using the String.Remove() method. It returns a new string in which a specified number of characters from the string are deleted. The following sample illustrates the use of the Remove() method.

Download  Run Code

 
The above code throws System.ArgumentOutOfRangeException if the length refers to a location outside the string. This can be handled by simply performing the length check.

Download  Run Code

 
In order to replace a portion of a string with another string, you can invoke the String.Insert() method on the resultant string, as shown below:

Download  Run Code

 
It’s better to create a string extension method, ReplaceAt(), which replaces the characters in the current string beginning at the specified position, with the replacement string.

Download  Run Code

 
Here’s an alternative method using the StringBuilder class. The benefit of using StringBuilder is that it considerably improves the code’s readability.

Download  Run Code

That’s all about removing or replacing a substring from a string in C#.