ExtensionMethod.NET Home of 819 C#, Visual Basic, F# and Javascript extension methods

IndexOfOccurence

Finds the index of the nth occurrence of a string in a string

Source

public static int IndexOfOccurence(this string str, string stringToBeFound, int occurrence)
{
    int occurrenceCounter = 0;
    int indexOfPassedString = 0 - stringToBeFound.Length;

    do
    {
        indexOfPassedString = str.IndexOf(stringToBeFound, indexOfPassedString + stringToBeFound.Length);
        if (indexOfPassedString == -1)
            break;
        occurrenceCounter++;
    }
    while (occurrenceCounter != occurrence);

    return indexOfPassedString;
}

Example

Console.WriteLine(IndexOfOccurence("Emad Alashi found ash on his desk, he went mad, very mad", "mad", 2));

Author: Emad Alashi

Submitted on: 27 apr 2011

Language: C#

Type: System.String

Views: 3447