Find Nth occurrence of a character in a string

public int GetNthIndex(string s, char t, int n)
{
    int count = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (s[i] == t)
        {
            count++;
            if (count == n)
            {
                return i;
            }
        }
    }
    return -1;
}

That could be made a lot cleaner, and there are no checks on the input.

Leave a Comment