Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

.NETASP.NETC#CodeProject
Home›.NET›Find Occurrence Of A String

Find Occurrence Of A String

By SibeeshVenu
August 5, 2015
1039
0
Share:

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

    TagsAsp.NetC-Sharp FunctionsC#Find Occurrence of StringFind String Form StringRegexString Contains SubstringSubstring
    Previous Article

    Find And Exclude Element From Array

    Next Article

    Remove An Array Element By Index

    0
    Shares
    • 0
    • +
    • 0
    • 0
    • 0

    SibeeshVenu

    I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

    Related articles More from author

    • .NETASP.NETC#Interview

      C sharp Interview Questions And Answers

      October 24, 2015
      By SibeeshVenu
    • Add_References
      .NETASP.NETWeb API

      Caching In Web API

      March 24, 2016
      By SibeeshVenu
    • jQuery Datatable With Server Side Data
      .NETAngularWeb API

      jQuery Datatable With Server Side Data

      February 25, 2016
      By SibeeshVenu
    • Creating Entity
      .NETASP.NET

      Working with API help page controller action description in Web API

      May 12, 2016
      By SibeeshVenu
    • .NETASP.NETSQL

      Passing a DataTable to a Stored Procedure

      May 31, 2015
      By SibeeshVenu
    • .NETASP.NET

      Determine Which Browser Your Application is Running In

      June 17, 2015
      By SibeeshVenu
    0

    My book

    Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

    YouTube

    MICROSOFT MVP (2016-2022)

    profile for Sibeesh Venu - Microsoft MVP

    Recent Posts

    • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
    • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
    • Easily move data from one COSMOS DB to another
    • .NET 8 New and Efficient Way to Check IP is in Given IP Range
    • Async Client IP safelist for Dot NET
    • Post Messages to Microsoft Teams Using Python
    • Get Azure Blob Storage Blob Metadata Using PowerShell
    • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
    • Integrate Azure App Insights in 1 Minute to .Net6 Application
    • Azure DevOps Service Connection with Multiple Azure Resource Group

    Tags

    Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
    • .NET
    • Achievements
    • ADO.NET
    • Android
    • Angular
    • Arduino
    • Article Of The Day
    • ASP.NET
    • Asp.Net Core
    • Automobile
    • Awards
    • Azure
    • Azure CDN
    • azure devops
    • Blockchain
    • Blog
    • Browser
    • C-Sharp Corner
    • C#
    • Career Advice
    • Code Snippets
    • CodeProject
    • Cognitive Services
    • Cosmos DB
    • CSS
    • CSS3
    • Data Factory
    • Database
    • Docker
    • Drawings
    • Drill Down Chart
    • English
    • Excel Programming
    • Exporting
    • Facebook
    • Fun
    • Gadgets
    • GitHub
    • GoPro
    • High Map
    • HighChart
    • How to
    • HTML
    • HTML5
    • Ignite UI
    • IIS
    • Interview
    • IoT
    • JavaScript
    • JQuery
    • jQuery UI
    • JQWidgets
    • JQX Grid
    • Json
    • Knockout JS
    • Linux
    • Machine Learning
    • Malayalam
    • Malayalam Poems
    • MDX Query
    • Microsoft
    • Microsoft ADOMD
    • Microsoft MVP
    • Microsoft Office
    • Microsoft Technologies
    • Microsoft Windows
    • Microsoft Windows Server
    • Mobile
    • MongoDB
    • Monthly Winners
    • MVC
    • MVC Grid
    • MySQL
    • News
    • Node JS
    • npm
    • Number Conversions
    • October 2015
    • Office 365
    • Office Development
    • One Plus
    • Outlook
    • Page
    • PHP
    • Poems
    • PowerShell
    • Products
    • Q&A
    • Raspberry PI
    • React
    • SEO
    • SharePoint
    • Skype
    • Social Media
    • Software
    • Spire.Doc
    • Spire.PDF
    • Spire.XLS
    • SQL
    • SQL Server
    • SSAS
    • SSMS
    • Storage In HTML5
    • Stories
    • Third Party Software Apps
    • Tips
    • Tools
    • Translator Text
    • Uncategorized
    • Unit Testing
    • UWP
    • VB.Net
    • Videos
    • Virtual Machine
    • Visual Studio
    • Visual Studio 2017
    • Wamp Server
    • Web API
    • Web Platform Installer
    • Webinars
    • WebMatrix
    • Windows 10
    • Windows 7
    • Windows 8.1
    • Wordpress
    • Writing

    ABOUT ME

    I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

    Contact Me

    • info@sibeeshpassion.com

    Pages

    • About
    • Search
    • Privacy Policy
    • About
    • Search
    • Privacy Policy
    © Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
    Go to mobile version