How to Remove a substring from a string in C#
This tutorial explains how to remove a string from a string in C#.
This tutorial will show you three different ways to remove substrings from a string.
Learn also:
Removing a string from a string with the string Replace method
One easy way to remove substrings from a substring is to use the string Replace method.
The following sample code removes "C# Programing" from "Online C# Programming Tutorials":
using System; namespace CSharp_Remove_String_From_String_Example { class Program { static void Main(string[] args) { string textString = "Online C# Programming Tutorials"; string stringToRemove = "C# Programming"; //Replace with an empty string //string emptyString = ""; string emptyString = string.Empty; string newTextString = textString.Replace(stringToRemove, emptyString); //Write to the console Console.WriteLine(newTextString); } } }
Output:
Online Tutorials
Removing a string from a string with the string Join and Split methods
Another easy way to remove a string from a string is to use the string Join and Split methods.
The following sample code shows an example of removing a string from a string using Join() and Split():
using System; namespace CSharp_Remove_String_From_String_Example { class Program { static void Main(string[] args) { string textStrings = "Let's learn C# programming! There are many C# programming tutorials."; string newString = string.Join("", textStrings.Split("C# programming")); //Write to the console Console.WriteLine(newString); } } }
Output:
Let's learn ! There are many tutorials.
Removing the first occurrence of a substring
If you want to remove only the first occurrence of a substring from a string, you can use Remove and IndexOf.
Sample code:
using System; namespace CSharp_Remove_String_From_String_Example { class Program { static void Main(string[] args) { string textString = "Online C# Programming Tutorials! Best C# Programming Books!"; string stringToRemove = "C# Programming"; //Find the index int index = textString.IndexOf(stringToRemove); //Get the length of the string to remove int length = stringToRemove.Length; //Remove string newTextString = textString.Remove(index, length); //Write to the console Console.WriteLine(newTextString); } } }
Output:
Online Tutorials! Best C# Programming Books!
Summary
In this tutorial, you have learned how to remove a substring from a string in C# using three different ways.