C#.Net Code to Count occurrences of String in Another String
In this post, here is the C# code to count the occurrences of a particular string in a given string.
Suppose there is a case where we may want to check whether the string contains particular substring or not. And we may want to count the occurrences of the substring, in that case you can use this method and if count =0, then it means the substring is not found.
Below are the 2 codes for the same method, you can use whatever you want.
Method 1 :
Suppose there is a case where we may want to check whether the string contains particular substring or not. And we may want to count the occurrences of the substring, in that case you can use this method and if count =0, then it means the substring is not found.
Below are the 2 codes for the same method, you can use whatever you want.
Method 1 :
/// <summary>
/// Method to Count occurrences of String in Another String
/// </summary>
/// <param name=”inputString”></param>
/// <param name=”searchStr”></param>
/// <param name=”matchCase”>True-MatchCase, False-IgnoreCase</param>
/// <returns></returns>
public int CountOfStrInStr(string inputString, string searchStr, bool matchCase)
{
int count = 0, TempLenth = 0;
if (!matchCase)
{
inputString = inputString.ToLower();
searchStr = searchStr.ToLower();
}
while ((TempLenth = inputString.IndexOf(searchStr, TempLenth)) != -1)
{
//incrementing lenth after finding string
TempLenth += searchStr.Length;
count++;
}
return count;
}
Method 2 :
/// <summary>
/// Method to Count occurrence in String in Another String using Regex
/// </summary>
/// <param name=”inputString”></param>
/// <param name=”searchStr”></param>
/// <param name=”matchCase”>True-MatchCase, False-IgnoreCase</param>
/// <returns>count of SubString found in string</returns>
/// <remarks>Namespace needed System.Text.RegularExpressions;</remarks>
public int CountOfStrInStr(string inputString, string searchStr, bool matchCase)
{
int count = 0;
if (matchCase)
{
count = Regex.Matches(inputString, searchStr).Count;
}
else
{
count = Regex.Matches(inputString, searchStr, RegexOptions.IgnoreCase).Count;
}
return count;
}