c# - How to remove a substring from a string

String remove substring
The following asp.net c# example code demonstrate us how can we remove a substring from a string programmatically at run time in an asp.net application. .Net framework's String.Remove() method allow us to remove specified characters (range of characters) from a string and return a new string object.

String.Remove(Int32, Int32) overloaded member allow us to return a new string in which a specified number of characters in the current instance beginning at a specified index position have been deleted. So, we can delete specified number of characters from a string which are beginning at a specified index position.

So, to delete a substring from a string, we need to know the starting index value of this substring and the length of this substring (number of characters in substring).

String.IndexOf(String) overloaded method reports the zero-based index of the first occurrence of the specified string in this instance. String.Length property return the number of characters in the instance string.

Finally, we can delete/remove a substring from a string by this way String.Remove(String.IndexOf(Substring), Substring.Length).

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this section create a string variable.
        string plants = "Clumpfoot Cabbage. California Walnut. Catalina Ironwood";

        Label1.Text = "string of plants..................<br />";
        Label1.Text += plants+"<br />";

        //substring to remove from string.
        string substring = "Cabbage";

        //this line get index of substring from string
        int indexOfSubString = plants.IndexOf(substring);
        //remove specified substring from string
        string withoutSubString = plants.Remove(indexOfSubString, substring.Length);

        Label1.Text += "<br />string removed substring...........";
        Label1.Text += "<br />" + withoutSubString;
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string remove substring</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string remove substring
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="string remove substring"  
More c# examples