Find Occurrence Of A String

In this article you will learn the ways to find the occurrence of a string from a string, or find a sub string from a string. We are using C# language to do this demo. In times, you may have faced this requirement. And I am sure you would do that. This article is for the one who don’t know how to achieve this. We will be discussing two methods here. I hope you will like it.

See demo

Occurrence Of A String Demo

Background

Today I have got a requirement of creating a function which performs some operations according to the occurrence of a string in a given string. Like, if a string pattern contains more that one time in a given string, it must do some actions and if it is just one time it should do other actions. I have done this in two ways, here I am sharing you that. I hope some one may find it is useful.

Using the code

We are going to discuss the following two ways to achieve this requirement.

  • Using Regex Class
  • Using Custom Function
  • We will start with a Regex class first.

    To start with Regex, you need to add another namespace as given below.

    [csharp]
    using System.Text.RegularExpressions;
    [/csharp]

    Now consider we have designed our page as follows.

    [html]
    <div>
    <table >
    <tr>
    <td>
    <asp:Label ID="lblInputString" runat="server" Text="Input String"></asp:Label>
    </td>
    <td>
    <textarea id="txtInputString" runat="server"></textarea>
    </td>
    </tr>
    <tr>
    <td>
    <asp:Label ID="lblPattern" runat="server" Text="Pattern String"></asp:Label>
    </td>
    <td>
    <textarea id="txtPattern" runat="server"></textarea>
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <asp:Button ID="btnCheckOccurance" runat="server" Text="Check Occurance" OnClick="btnCheckOccurance_Click" />
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <asp:Label ID="lblOutput" runat="server" Text="See Output Here!!! <i> Thank you for visiting. Please Visit Again!!! </i>"></asp:Label>
    </td>
    </tr>
    </table>
    </div>
    [/html]

    And Some CSS styles as follows.

    [css]
    <style type="text/css">
    textarea {
    width: 630px;
    height: 100px;
    }

    table {
    border: 1px solid #ccc;
    padding: 10px;
    width: 800px;
    text-align:center;
    }

    tr {
    border: 1px solid #999;
    border-radius: 5px;
    }

    td {
    border: 1px solid #999;
    padding: 10px;
    border-radius: 5px;
    }
    </style>
    [/css]

    If you add the above codes and CSS, your page may looks like in the preceding image.

    Now we will see our C# code. Please add the below lines of codes in the button click event.

    [csharp]
    protected void btnCheckOccurance_Click(object sender, EventArgs e)
    {
    int occuranceCount = 0;

    //Checking Occurance
    occuranceCount = Regex.Matches(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim()).Count;
    if (occuranceCount > 0)
    lblOutput.Text = "<br/><br/><b>Sibeesh Passion </b>Says <br/><br/>The given string pattern <i>" + txtPattern.Value + "</i> Contains " + occuranceCount + " times in <i>"
    + txtInputString.Value + "</i><br/><br/> Thank you for visiting. Please Visit Again!!!";
    else
    lblOutput.Text = "<br/><br/><b>Sibeesh Passion </b>Says <br/><br/>The given string pattern <i>" + txtPattern.Value + "</i> Is not occured s in <i>"
    + txtInputString.Value + "</i><br/><br/> Thank you for visiting. Please Visit Again!!!";
    //End
    }
    [/csharp]

    In the above code, we are finding the occurrence of a string by using a Regex.Matches function. The Regex.Matches function expects two parameters.

  • Input String (In which string we need to search for a string)
  • Pattern String(What we need to search in a string)
  • We are getting those two values from our texarea and pass as follows.

    [csharp]
    Regex.Matches(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim()).Count;
    [/csharp]

    Now if you run application, you will get output as follows.

    Find_Occurrence_Of_A_String_Using_Regex

    Find_Occurrence_Of_A_String_Using_Regex_2

    As you can see I have given the words, “Sibeesh” and “passion” for testing, and it gave the correct number of occurrence right?

    Now we will see how we can do this by Using a Custom Function.

    Following in our function call.

    [csharp]
    occuranceCount = FindOccurrences(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim());
    [/csharp]

    And please find the function body below.

    [csharp]
    #region FindOccurrences
    /// <summary>
    /// This method is used to get the Count of Occurrences of a string in a string
    /// </summary>
    /// <param name="InputString"></param>
    /// <param name="patternString"></param>
    /// <returns>Int</returns>
    public int FindOccurrences(string InputString, string patternString)
    {
    // Here we are looping through InputString
    int intCount = 0;
    int i = 0;
    while ((i = InputString.IndexOf(patternString, i)) != -1)
    {
    i += patternString.Length;
    intCount++;
    }
    return intCount;
    }
    #endregion
    [/csharp]

    Now if your run you will get the same output as we got by using a Regex function.

    Find_Occurrence_Of_A_String_Using_Custom_Function

    Find_Occurrence_Of_A_String_Using_Custom_Function_2

    Now we will see our complete codes.

    Complete Code

    Default.aspx.cs

    [csharp]
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnCheckOccurance_Click(object sender, EventArgs e)
    {
    int occuranceCount = 0;

    //Checking Occurance
    //occuranceCount = Regex.Matches(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim()).Count;
    occuranceCount = FindOccurrences(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim());
    if (occuranceCount > 0)
    lblOutput.Text = "<br/><br/><b>Sibeesh Passion </b>Says <br/><br/>The given string pattern <i>" + txtPattern.Value + "</i> Contains " + occuranceCount + " times in <i>"
    + txtInputString.Value + "</i><br/><br/> Thank you for visiting. Please Visit Again!!!";
    else
    lblOutput.Text = "<br/><br/><b>Sibeesh Passion </b>Says <br/><br/>The given string pattern <i>" + txtPattern.Value + "</i> Is not occured s in <i>"
    + txtInputString.Value + "</i><br/><br/> Thank you for visiting. Please Visit Again!!!";
    //End
    }
    #region FindOccurrences
    /// <summary>
    /// This method is used to get the Count of Occurrences of a string in a string
    /// </summary>
    /// <param name="InputString"></param>
    /// <param name="patternString"></param>
    /// <returns>Int</returns>
    public int FindOccurrences(string InputString, string patternString)
    {
    // Here we are looping through InputString
    int intCount = 0;
    int i = 0;
    while ((i = InputString.IndexOf(patternString, i)) != -1)
    {
    i += patternString.Length;
    intCount++;
    }
    return intCount;
    }
    #endregion
    }
    [/csharp]

    Default.aspx

    [html]
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Find Occurrence of String,Find String Form String,Regex,String Contains Substring – Sibeesh Passion</title>
    <style type="text/css">
    textarea {
    width: 630px;
    height: 100px;
    }

    table {
    border: 1px solid #ccc;
    padding: 10px;
    width: 800px;
    text-align:center;
    }

    tr {
    border: 1px solid #999;
    border-radius: 5px;
    }

    td {
    border: 1px solid #999;
    padding: 10px;
    border-radius: 5px;
    }
    </style>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <table >
    <tr>
    <td>
    <asp:Label ID="lblInputString" runat="server" Text="Input String"></asp:Label>
    </td>
    <td>
    <textarea id="txtInputString" runat="server"></textarea>
    </td>
    </tr>
    <tr>
    <td>
    <asp:Label ID="lblPattern" runat="server" Text="Pattern String"></asp:Label>
    </td>
    <td>
    <textarea id="txtPattern" runat="server"></textarea>
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <asp:Button ID="btnCheckOccurance" runat="server" Text="Check Occurance" OnClick="btnCheckOccurance_Click" />
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <asp:Label ID="lblOutput" runat="server" Text="See Output Here!!! <i> Thank you for visiting. Please Visit Again!!! </i>"></asp:Label>
    </td>
    </tr>
    </table>
    </div>
    </form>
    </body>
    </html>
    [/html]

    Validation

    Now if you want you can add some basic validation to your code in server side and client side. I will always recommend you to do both validation.

    Server Side
    [csharp]
    if (txtInputString.Value.ToLower().Trim() != "" && txtPattern.Value.ToLower().Trim() != "")
    {
    }
    [/csharp]

    Place the button click event code inside of this if condition.

    Client Side

    Add a Jquery reference

    [js]
    <script src="jquery-2.0.2.min.js"></script>
    [/js]

    And add the below scripts.

    [js]
    <script>
    $(document).ready(function () {
    $(‘#btnCheckOccurance’).click(function () {
    if ($(‘#txtInputString’).val() == "" || $(‘#txtPattern’).val() == "") {
    alert(‘Values can not be empty’);
    return false;
    }
    });
    });
    </script>
    [/js]

    Conclusion

    I hope someone found this article useful. Please share me your valuable thoughts and comments. Your feedback is always welcomed.

    Thanks in advance. Happy coding!

    Kindest Regards
    Sibeesh Venu

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Serverless 360