c# - How to find a substring within a string

String find substring
The following asp.net c# example code demonstrate us how can we find a substring within a string object programmatically at run time in an asp.net application. .Net framework's String Class has a built in method to find/search a substring from a string value.

String Class String.Contains() method return a value indicating whether a specified substring occurs within this string instance. This method require to pass a parameter named 'value' which represent the substring to seek. Contains() method return a Boolean value. If the method find the specified substring in the string then it return 'true'; otherwise it return false.

So, if we want to search the substring 'sample' from the string 'a sample text', then we can call the Contains() method as String.Contains("sample"). Method returns value 'true' indicate the specified substring found in string.

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

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this section create string variables.
        string plants = "Sweet Potato Vine, Thimbleweed , Annual Sow Thistle";

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

        string substringToFind = "Potato";
        string substringToFind2 = "Sycamore";

        //this line find/search substring [Potato] in string
        Boolean result = plants.Contains(substringToFind);

        //this line find/search substring [Sycamore] in string
        Boolean result2 = plants.Contains(substringToFind2);

        Label1.Text += "<br /><br />plants exists [Potato]? " + result.ToString();
        Label1.Text += "<br />plants exists [Sycamore]? " + result2.ToString();
        //another option to find/search substring in string
        if (plants.IndexOf(substringToFind) != -1)
            Label1.Text += "<br />plants exists Potato in index of: ";
            Label1.Text += plants.IndexOf(substringToFind);
        if (plants.IndexOf(substringToFind2) != -1)
            Label1.Text += "<br />plants exists Sycamore in index of: ";
            Label1.Text += plants.IndexOf(substringToFind);
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string find substring</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string find substring
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="string find substring"  
More c# examples