C# Program To Find The Count Of Sub-string "SHL" In A Given String

C# Program to find the count of sub-string "SHL" in a given String.
This is a simplified version of a problem, we will consider a generic program for any substring as well, but to understand the concept we will see how to count how many times "SHL" comes in a given string.
If you're a beginner in the coding world your main aim is to solve the problem and produce the required answer by simply understanding the problem and generating logic but with time the aim shifts from solving the problem in minimum steps. We will consider two solutions for this specific program. One being a simple newbie logic and the other one is the most simplified form for this problem.

Straight Forward Approach

In this approach, we simply run a loop to check each char of the string, and if it meets our requirement such that the first char is ‘S’ second is ‘H’ and third is ‘L’ we will increment our counter that we initialized at the beginning of the program. Check out the code.
  1. using System;      
  3. public class MyClass{      
  4.     public static void Main(){      
  5.         string str = "SHLfjsSHLfsjfshl".ToUpper();        
  6.        //Counter Keeping the track    
  7.         int c = 0;      
  8.         for(int i=0;i<str.Length;i++)      
  9.         {      
  10.             if(str[i]=='S'){      
  11.                 if(str[i+1]=='H'){      
  12.                     if(str[i+2]=='L'){      
  13.                         c+=1;      
  14.                     }      
  15.                 }      
  16.             }      
  17.         }      
  19.     Console.WriteLine(c);      
  20.     }      
  21. }      

Smart Approach

Well for this solution we are gonna dive into one of the most brilliant topics in computer science, “Regular Expression”. For More detail refer to the reference links attached below. This solution acts as a generic solution as well. In place of "SHL" ou can pass any possible substring you want to count.
  1. using System;      
  2. using System.Text.RegularExpressions;    
  4. public class MyClass{    
  5.     public static void Main(){    
  6.         string str = "SHLfjsSHLfsjfshl".ToUpper();    
  7.         int c = Regex.Matches(str, "SHL").Count;    
  9.     Console.WriteLine(c);    
  10.     }    
  11. }    
Common Output
C# Program to find the count of sub-string "SHL" in a given String
  1. https://www.tutorialspoint.com/csharp/csharp_regular_expressions.htm
  2. https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=net-5.0