Get index of nth occurrence of char in a string

后端 未结 9 1859
情书的邮戳
情书的邮戳 2020-12-06 00:44

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(s         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 01:07

    Not tested but something like this should work:

    private int IndexOfNth(string str, char c, int n)
    {
        int index = -1;
        while (n-- > 0)
        {
            index = str.IndexOf(c, index + 1);
            if (index == -1) break;
        }
        return index;
    }
    

提交回复
热议问题