Skip to content

Instantly share code, notes, and snippets.

@ermakovich
Last active December 21, 2015 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ermakovich/6229341 to your computer and use it in GitHub Desktop.
Save ermakovich/6229341 to your computer and use it in GitHub Desktop.
Extension method for the System.String class, that reports the index of the N-th occurence of a specified string within the current System.String object.
namespace System
{
public static class StringExtensions
{
/// <summary>
/// Reports the index of the N-th occurence of a specified string within the current System.String object.
/// </summary>
/// <param name="source">Source string.</param>
/// <param name="value">The string to seek.</param>
/// <param name="n">
/// Zero-based index, representing N-th occurrence of a specified string within the current System.String
/// object.
/// </param>
/// <returns></returns>
public static int NthIndexOf(this string source, string value, int n)
{
int result = 0;
while (true)
{
int index = source.IndexOf(value, StringComparison.Ordinal);
if (index < 0)
{
return index;
}
result += index;
if (n == 0)
{
return result;
}
result += value.Length;
source = source.Substring(index + value.Length);
n--;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment