Tuesday, August 17, 2010

How to get Nth IndexOf a string



using System.Text.RegularExpressions;
public class Utility
{
    public static int GetNthIndexOf(string str, string match, int n)
    {
        Match m = Regex.Match(str, "((" + match + ").*?){" + n + "}");
 
        if (m.Success)
            return m.Groups[2].Captures[n - 1].Index;
        else
            return -1;
    }
 
 
    public static int GetNthIndexOf(string str, string match, int n)
    {
        int i = 1;
        int index = -1;
        while (((index = str.IndexOf(match, index + 1)) != -1) && (i <= n))
        {
            if (i == n) return index;
            i++;
        }
        return -1;
    }
}

0 comments:

Post a Comment