C# - String: Get the index of nth occurence

By , 10/1/2015
(0 ratings)
This extension methods returns the index of the nth occurences of the given substring.

Required Namespace
System
/// <summary>
/// Returns the index of the nth occurences of the given substring.
/// </summary>
/// <param name="source">The string to search in.</param>
/// <param name="pattern">The searched substring.</param>
/// <param name="ignore">The number of occurences to ignore.</param>
/// <returns>The index of <paramref name="pattern"/> in <paramref name="source"/> after <paramref name="ignore"/> occurences.</returns>
public static int IndexOfNthOccurence(this string source, string pattern, uint ignore)
{
    return IndexOfNthOccurence(source, pattern, ignore, StringComparison.CurrentCulture);
}

/// <summary>
/// Returns the index of the nth occurences of the given substring.
/// </summary>
/// <param name="source">The string to search in.</param>
/// <param name="pattern">The searched substring.</param>
/// <param name="ignore">The number of occurences to ignore.</param>
/// <param name="comparisonType">The comparison type.</param>
/// <returns>The index of <paramref name="pattern"/> in <paramref name="source"/> after <paramref name="ignore"/> occurences.</returns>
public static int IndexOfNthOccurence(this string source, string pattern, uint ignore, StringComparison comparisonType)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }
    if (pattern == null)
    {
        throw new ArgumentNullException("pattern");
    }
    if (pattern.Length == 0)
    {
        return -1;
    }

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

Comments

 

Log in, to comment!