C# - String: count occurences of a substring

By , 9/28/2015
(0 ratings)
This extension methods counts the occurences of a substring in a string.
Translate to VB
/// <summary>
/// Counts the occurences of a substring in a string.
/// </summary>
/// <param name="source">The string to be searched.</param>
/// <param name="pattern">The searched substring.</param>
/// <returns>The count of <paramref name="pattern"/> in <paramref name="source"/>.</returns>
public static int CountOccurences(this string source, string pattern)
{
    return CountOccurences(source, pattern, StringComparison.CurrentCulture);
}

/// <summary>
/// Counts the occurences of a substring in a string.
/// </summary>
/// <param name="source">The string to be searched.</param>
/// <param name="pattern">The searched substring.</param>
/// <param name="comparisonType">The comparison to use.</param>
/// <returns>The count of <paramref name="pattern"/> in <paramref name="source"/>.</returns>
public static int CountOccurences(this string source, string pattern, StringComparison comparisonType)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (pattern == null)
    {
        throw new ArgumentNullException("pattern");
    }
    if (!Enum.IsDefined(typeof(StringComparison), comparisonType))
    {
        throw new ArgumentOutOfRangeException("comparisonType");
    }
    if (pattern.Length == 0)
    {
        return -1;
    }

    int result = 0;
    int currentIndex = 0;
    while (currentIndex != -1)
    {
        currentIndex = source.IndexOf(pattern, currentIndex, comparisonType);
        if (currentIndex != -1)
        {
            result++;
            currentIndex++;
        }
    }
    return result;
}
Tagged with Extension, String, Count.

Comments

 

Log in, to comment!