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.
- using System;
-
- public class MyClass{
- public static void Main(){
- string str = "SHLfjsSHLfsjfshl".ToUpper();
-
- int c = 0;
- for(int i=0;i<str.Length;i++)
- {
- if(str[i]=='S'){
- if(str[i+1]=='H'){
- if(str[i+2]=='L'){
- c+=1;
- }
- }
- }
- }
-
- Console.WriteLine(c);
- }
- }
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.
- using System;
- using System.Text.RegularExpressions;
-
- public class MyClass{
- public static void Main(){
- string str = "SHLfjsSHLfsjfshl".ToUpper();
- int c = Regex.Matches(str, "SHL").Count;
-
- Console.WriteLine(c);
- }
- }
Common Output
REFERENCES
-
https://www.tutorialspoint.com/csharp/csharp_regular_expressions.htm
-
https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=net-5.0