Last active
December 21, 2015 01:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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