Find Occurrence of a String

This article shows various ways to find the occurrence of a string in another string, or how to find a substring in a string. We are using the C# language to do this demo. At times, you may have encountered this requirement. This article is for those who don't know how to do this. We will be explaining two methods here. I hope you will like it.

Please see this article in my blog.

See demo.

Background

Today I got the requirement to create a function that does some operations depending on the occurrence of a string in a given string. Like, if a string pattern exists more than once in a given string, it must do some actions and if it occurs just once then it should do somethng else. I have done this in two ways, here I am sharing them. I hope you will find this useful.

Using the code

We will explain the following two ways to satisfy 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 in the following:

  1. using System.Text.RegularExpressions;   
Now consider we have designed our page as in the following code snippet:
  1. <div>  
  2.     <table >  
  3.         <tr>  
  4.             <td>  
  5.                 <asp:Label ID="lblInputString" runat="server" Text="Input String"></asp:Label>  
  6.             </td>  
  7.             <td>  
  8.                 <textarea id="txtInputString" runat="server"></textarea>  
  9.             </td>  
  10.         </tr>  
  11.         <tr>  
  12.             <td>  
  13.                 <asp:Label ID="lblPattern" runat="server" Text="Pattern String"></asp:Label>  
  14.             </td>  
  15.             <td>  
  16.                 <textarea id="txtPattern" runat="server"></textarea>  
  17.             </td>  
  18.         </tr>  
  19.         <tr>  
  20.             <td colspan="2">  
  21.                 <asp:Button ID="btnCheckOccurance" runat="server" Text="Check Occurance" OnClick="btnCheckOccurance_Click" />  
  22.             </td>  
  23.         </tr>  
  24.         <tr>  
  25.             <td colspan="2">  
  26.                 <asp:Label ID="lblOutput" runat="server" Text="See Output Here!!!   
  27.                     <i> Thank you for visiting. Please Visit Again!!! </i>">  
  28.                 </asp:Label>  
  29.             </td>  
  30.         </tr>  
  31.     </table>  
  32. </div>    

And some CSS styles as follows.

  1. <style type="text/css">      
  2. textarea {    
  3.   width630px;    
  4.   height100px;    
  5. }    
  6.     
  7. table {    
  8.   border1px solid #ccc;    
  9.   padding10px;    
  10.   width800px;    
  11.   text-aligncenter;    
  12. }    
  13.     
  14. tr {    
  15.   border1px solid #999;    
  16.   border-radius: 5px;    
  17. }    
  18.     
  19. td {    
  20.   border1px solid #999;    
  21.   padding10px;    
  22.   border-radius: 5px;    
  23. }      
  24. </style> 

If you add the preceding code and CSS, your page may look such as in the preceding image.

String

Now we will see our C# code. Please add the following lines of code on the button click event.

  1. protected void btnCheckOccurance_Click(object sender, EventArgs e)   
  2. {  
  3.     int occuranceCount = 0;  
  4.     //Checking Occurance      
  5.     occuranceCount = Regex.Matches(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim()).Count;  
  6.     if (occuranceCount > 0)   
  7.     {  
  8.         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!!!";  
  9.     }   
  10.     else   
  11.     {  
  12.         lblOutput.Text = "<br/>
  13.    <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!!!";  
  14.         //End      
  15.     }  
  16.   

In the preceding code, we are finding the occurrence of a string using a Regex.Matches function. TheRegex.Matches function expects two parameters.

  • Input String (the string to be searched)
  • Pattern String (What we need to search for in the string)

We are getting those two values from our textarea and pass as follows.

  1. Regex.Matches(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim()).Count;  

Now if you run the application, you will get the following output:

String

pattern String

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

Now we will see how to do this using a Custom Function.

The following is our function call.

  1. occuranceCount = FindOccurrences(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim());  

And here's the function body:

  1. #region FindOccurrences    
  2. /// <summary>      
  3. /// This method is used to get the Count of Occurrences of a string in a string      
  4. /// </summary>      
  5. /// <param name="InputString"></param>      
  6. /// <param name="patternString"></param>      
  7. /// <returns>Int</returns>      
  8. public int FindOccurrences(string InputString, string patternString) {    
  9.     // Here we are looping through InputString      
  10.     int intCount = 0;    
  11.     int i = 0;    
  12.     while ((i = InputString.IndexOf(patternString, i)) != -1) {    
  13.         i += patternString.Length;    
  14.         intCount++;    
  15.     }    
  16.     return intCount;    
  17. }
  18. #endregion  

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

input string

Check Occurance

Now we will see the complete code.

Complete Code

Default.aspx.cs

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text.RegularExpressions;    
  5. using System.Web;    
  6. using System.Web.UI;    
  7. using System.Web.UI.WebControls;    
  8. public partial class _Default: System.Web.UI.Page {    
  9.     protected void Page_Load(object sender, EventArgs e) {}    
  10.     protected void btnCheckOccurance_Click(object sender, EventArgs e) {    
  11.         int occuranceCount = 0;    
  12.         //Checking Occurance      
  13.         //occuranceCount = Regex.Matches(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim()).Count;      
  14.         occuranceCount = FindOccurrences(txtInputString.Value.ToLower().Trim(), txtPattern.Value.ToLower().Trim());    
  15.         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!!!";    
  16.         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!!!";    
  17.         //End      
  18.     }#region FindOccurrences    
  19.     /// <summary>      
  20.     /// This method is used to get the Count of Occurrences of a string in a string      
  21.     /// </summary>      
  22.     /// <param name="InputString"></param>      
  23.     /// <param name="patternString"></param>      
  24.     /// <returns>Int</returns>      
  25.     public int FindOccurrences(string InputString, string patternString) {    
  26.         // Here we are looping through InputString      
  27.         int intCount = 0;    
  28.         int i = 0;    
  29.         while ((i = InputString.IndexOf(patternString, i)) != -1) {    
  30.             i += patternString.Length;    
  31.             intCount++;    
  32.         }    
  33.         return intCount;    
  34.     }#endregion    
  35. }  

Default.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html>  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title>Find Occurrence of String,Find String Form String,Regex,String Contains Substring - Sibeesh Passion</title>  
  7.         <style type="text/css">      
  8.             textarea {      
  9.                 width: 630px;      
  10.                 height: 100px;      
  11.             }      
  12.             table {      
  13.                 border: 1px solid #ccc;      
  14.                 padding: 10px;      
  15.                 width: 800px;      
  16.                 text-align:center;      
  17.             }      
  18.             tr {      
  19.                 border: 1px solid #999;      
  20.                 border-radius: 5px;      
  21.             }      
  22.             td {      
  23.                 border: 1px solid #999;      
  24.                 padding: 10px;      
  25.                 border-radius: 5px;      
  26.             }      
  27.         </style>  
  28.     </head>  
  29.     <body>  
  30.         <form id="form1" runat="server">  
  31.             <div>  
  32.                 <table >  
  33.                     <tr>  
  34.                         <td>  
  35.                             <asp:Label ID="lblInputString" runat="server" Text="Input String"></asp:Label>  
  36.                         </td>  
  37.                         <td>  
  38.                             <textarea id="txtInputString" runat="server">  
  39.                                 <asp:label id="lblPattern" runat="server" text="Pattern String"></asp:label>  
  40.                                 <textarea id="txtPattern" runat="server">  
  41.                                 <asp:button id="btnCheckOccurance" runat="server" text="Check Occurance" onclick="btnCheckOccurance_Click">  
  42.                                     <asp:label id="lblOutput" runat="server" text="See Output Here!!! > Thank you for visiting. Please Visit Again!!! </i>">  
  43.                                     </asp:label>  
  44.                                 </asp:button>                         
  45.                               
  46.                                 <asp:label id="lblOutput" runat="server" text="See Output Here!!!   
  47.                                     <i> Thank you for visiting. Please Visit Again!!! </i>">  
  48.                                 </asp:label>
  49.                           </td>
                         </tr>
                      </table>
                   </div>
                </form>
             </body>
       </htm>

Validation

You can also add some basic validation to your code on the server-side and the client-side. I will always recommend you to do both the validations.

Server-Side

  1. if (txtInputString.Value.ToLower().Trim() != "" && txtPattern.Value.ToLower().Trim() != "")  
  2. {  
  3. }  

Place the button click event code inside this if condition.

Client-Side

Add a jQuery reference.

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

And add the following scripts:

  1. < script > 
  2.    $(document).ready(function() {    
  3.        $('#btnCheckOccurance').click(function() {    
  4.            if ($('#txtInputString').val() == "" || $('#txtPattern').val() == "") {    
  5.                alert('Values can not be empty');    
  6.                return false;    
  7.            }    
  8.        });    
  9.    }); 
  10. < /script> 

Conclusion

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


Similar Articles