I've found a nice extension method that finds Nth occurrence of value
into some input
string:
public static int IndexOfNth(this string input, string value, int startIndex, int nth)
{
if (nth < 1)
throw new ArgumentException("Can not find the zeroth index of substring in string. Must start with 1");
if (nth == 1)
return input.IndexOf(value, startIndex, StringComparison.Ordinal);
var idx = input.IndexOf(value, startIndex, StringComparison.Ordinal);
if (idx == -1)
return -1;
return input.IndexOfNth(value, idx + value.Length, --nth);
}
I need the next one, but can't transform it myself:
IndexOfNthFromEnd(this string input, string value, int nth)
It should find index of Nth occurrence from end of the string. For example:
IndexOfNthFromEnd("-!-!----", "!", 2) // = 1;
IndexOfNthFromEnd("-!-!----", "!", 1) // = 3;
IndexOfNthFromEnd("-!-!----", "-!", 2) // = 0;
IndexOfNthFromEnd("-!-!----", "-!", 1) // = 2;