c# - How to find all occurrences of a substring within a string

Find all occurrences of a substring within a String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can find all occurrences of a substring within a String. In this .net c# tutorial code we will find that a specified substring is how many times exists inside a String object. Such as we have a String instance, we have to find a substring ‘Cherry’ within it and we also have to show all the index positions of the ‘Cherry’ substring found within the String instance.

We can do this using a ‘while’ loop. We will loop through all occurrences of the specified substring inside the String instance. The loop will continue until there are no matching available. On the looping time, we also display the substring occurrences index position on the user interface.

We can find the index position of the specified substring within a String instance using the String IndexOf() method. The String IndexOf() method reports the zero-based index of the first occurrence of a specified Unicode character or String within this instance. The IndexOf() method returns -1 if the character or String is not found in the instance.

The String IndexOf(string value, int startIndex) method overload reports the zero-based index of the first occurrence of the specified String in this instance and the search starts at a specified character position.

<%@ 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 = "Black Cherry. Cabinet Cherry. Skunk Cabbage. Wild Cherry";

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

        //substring to find/search indexes/occurrences in string.
        string indexOfSubStringToFind = "Cherry";

        int index = 0;

        Label1.Text += "<br /><br />substring [Cherry] found in following index position in string";

        //find all indexes/occurrences of specified substring in string
        while ((index=plants.IndexOf(indexOfSubStringToFind, index)) != -1)
            Label1.Text += "<br />" + index;
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string find all occurrences</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string find all occurrences
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="string find all occurrences"  
More c# examples