Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of nth occurrence of char in a string

Tags:

string

c#

.net

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?

like image 330
Kyle V. Avatar asked Jul 06 '12 13:07

Kyle V.


People also ask

How do you find the index of a certain character in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the nth index of a character in a string in python?

You can find the nth occurrence of a substring in a string by splitting at the substring with max n+1 splits. If the resulting list has a size greater than n+1, it means that the substring occurs more than n times.


1 Answers

Don't do that; IndexOf takes a second parameter that specifies where to start.

private static int IndexOfNth(string str, char c, int n) {
    int s = -1;

    for (int i = 0; i < n; i++) {
        s = str.IndexOf(c, s + 1);

        if (s == -1) break;
    }

    return s;
}
like image 191
Ry- Avatar answered Sep 20 '22 20:09

Ry-