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));