Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Usuful methods – 9 of N – Count string occurences July 2, 2008

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 😉

Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s