C# Remove String from String

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":

  1. using System;
  2. namespace CSharp_Remove_String_From_String_Example
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string textString = "Online C# Programming Tutorials";
  9. string stringToRemove = "C# Programming";
  10. //Replace with an empty string
  11. //string emptyString = "";
  12. string emptyString = string.Empty;
  13. string newTextString = textString.Replace(stringToRemove, emptyString);
  14. //Write to the console
  15. Console.WriteLine(newTextString);
  16. }
  17. }
  18. }
  19.  

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():

  1. using System;
  2. namespace CSharp_Remove_String_From_String_Example
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string textStrings = "Let's learn C# programming! There are many C# programming tutorials.";
  9. string newString = string.Join("", textStrings.Split("C# programming"));
  10. //Write to the console
  11. Console.WriteLine(newString);
  12. }
  13. }
  14. }
  15.  

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:

  1. using System;
  2. namespace CSharp_Remove_String_From_String_Example
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string textString = "Online C# Programming Tutorials! Best C# Programming Books!";
  9. string stringToRemove = "C# Programming";
  10. //Find the index
  11. int index = textString.IndexOf(stringToRemove);
  12. //Get the length of the string to remove
  13. int length = stringToRemove.Length;
  14. //Remove
  15. string newTextString = textString.Remove(index, length);
  16. //Write to the console
  17. Console.WriteLine(newTextString);
  18. }
  19. }
  20. }

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.


See also:
C# List Contains with Examples
C# typeof with Examples
C# TryParse (int, double, float) with Examples
C# Data Types
C# Variables