Get index of nth occurrence of char in a string

Posted by StickFigs on Stack Overflow See other posts from Stack Overflow or by StickFigs
Published on 2012-07-06T13:26:02Z Indexed on 2012/07/06 15:15 UTC
Read the original article Hit count: 221

Filed under:
|
|

I'm trying to make a function that returns the index of the Nth occurrence of a given char in a string.

Here is my attempt:

private int IndexOfNth(string str, char c, int n)
{
    int index = str.IndexOf(c) + 1;
    if (index >= 0)
    {
        string temp = str.Substring(index, str.Length - index);
        for (int j = 1; j < n; j++)
        {
            index = temp.IndexOf(c) + 1;
            if (index < 0)
            {
                return -1;
            }
            temp = temp.Substring(index, temp.Length - index);
        }
        index = index + (str.Length);
    }
    return index;
}

This should find the first occurrence, chop off that front part of the string, find the first occurrence from the new substring, and on and on until it gets the index of the nth occurrence. However I failed to consider how the index of the final substring is going to be offset from the original actual index in the original string. How do I make this work?

Also as a side question, if I want the char to be the tab character do I pass this function '\t' or what?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET