Skip to main content

Count the number of times that a substring occurs in the text.

/// <summary>
/// Count the number of times that the substring occurs in the text.
/// </summary>
/// <param name="text">the text to search</param>
/// <param name="substring">the substring to find</param>
/// <returns>the number of times the substring occurs in the text</returns>
/// <remarks>
/// <para>
/// The substring is assumed to be non-repeating within itself.
/// </para>
/// </remarks>
private static int CountSubstrings(string text, string substring)
{
    var length = text.Length;
    if (length == 0)
    {
        return 0;
    }

    var substringLength = substring.Length;
    if (substringLength == 0)
    {
        return 0;
    }

    int count = 0, offset = 0;
    while (offset < length)
    {
        var index = text.IndexOf(substring, offset, StringComparison.Ordinal);
        if (index == -1)
        {
            break;
        }

        count++;
        offset = index + substringLength;
    }

    return count;
}