Usuful methods – 9 of N – Count string occurences
One more extension method(hopefully useful) on String. If we want to count how many times a string contains another string this method will help us.
public static int CountOccurences(this string original, string value)
{
return original.CountOccurences(value, StringComparison.CurrentCulture);
}
public static int CountOccurences(this string original, string value, StringComparison comparisionType)
{
return GenericCountOccurences(original, value, comparisionType, value.Length);
}
public static int CountOverlapOccurences(this string original, string value)
{
return GenericCountOccurences(original, value, StringComparison.CurrentCulture, 1);
}
public static int CountOverlapOccurences(this string original, string value, StringComparison comparisionType)
{
return GenericCountOccurences(original, value, comparisionType, 1);
}
private static int GenericCountOccurences(string original, string value, StringComparison comparisionType, int step)
{
int occurences = 0;
if (!string.IsNullOrEmpty(original))
{
int foundIndex = original.IndexOf(value, 0, comparisionType);
while (foundIndex >= 0)
{
occurences++;
foundIndex = original.IndexOf(value, foundIndex + step, comparisionType);
}
}
return occurences;
}
We have two versions – simple and overlapping.
When we use the simple version like this
var input = "aaaa";
var count = input.CountOccurences("aa");
we’ll have count = 2.
When we use the overlapping one on the same input
var input = "aaaa";
var count = input.CountOverlapOccurences("aa");
we’ll have count = 3.
That’s because the search of the next occurrence begins right after the start of the match and in the other version the search begins after the end of the previous match.
Note: I’m sure my colleague and friend Vlado will appreciate this

Leave a Reply