I was looking for a c# function to count the number of occurrences of a string in a string. But I couldn't find any by default.

So I wrote my own little function. Migth come in handy!

In this scenario I had a string that contains line feeds, I had to know how many to correctly calculate the length of the string. Here is the function that does the work:

public static int Count(string src, string find)
        {
            int ret = 0;
            int len = find.Length;
            for (int i=0; i < src.Length-len;i++)
            {
                if (src.Substring(i,len) == find)
                {
                    ++ret;
                }
            }
            return ret;
        }

So I was looking for "\r\n" in a string:

int countNewLines = Count(day.Remark,"\r\n");
 

It's Simple and easy, any person could find this, but I like to blog it so next time I won't have to look for it again.

This improved function by feedback of Tom is more performant:

private int countOccurences(string text, string toFind)
{
  return (toFind.Length > 0) ? 
  (text.Length - text.Replace(toFind, string.Empty).Length) / toFind.Length : 0;
}
 

I'll explain what happens: it returns the length of the text minus the lenght of the text without the string that you are looking for divided by the length of the search string.

Eg. text = aaaabgaabg to find = bg. string lenght = 10 - string lenght without bg = 6 makes 4. We divide 4 by the length of the search string bg = 2 makes 2 occurences: (10 - 6) /2=2