Skip to main content
3 of 8
added 10 characters in body
nhgrif
  • 25.4k
  • 3
  • 64
  • 129

Your current implementation could be more efficient. Copying the passed in string and chopping it up is probably pretty expensive (I'm not a master of .NET internals though).

public static int Occurences(this string str, string val)
{  
    int occurrences = 0;
    int startingIndex = 0;

    while ((startingIndex = str.IndexOf(val, startingIndex)) >= 0) 
    {
        ++occurrences;
        ++startingIndex;
    }

    return occurrences;
}

As a note, I'm unaware of the consequences of calling IndexOf with a startingIndex >= the length of the parent string. You may need to check for this.

nhgrif
  • 25.4k
  • 3
  • 64
  • 129