Get index of nth occurrence of char in a string

后端 未结 9 1837
情书的邮戳
情书的邮戳 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:16

    You could use the following method which will return the nth occurrence of the specified character within the designated string.

    public static int IndexOfNthCharacter(string str, int n, char c) {
        int index = -1;
        if (!str.Contains(c.ToString()) || (str.Split(c).Length-1 < n)) {
            return -1;
        }
        else {
            for (int i = 0; i < str.Length; i++) {
                if (n > 0) {            
                    index++;
                }
                else {
                    return index;
                }
                if (str[i] == c) {
                    n--;
                }
            }
            return index;
        }
    }
    

    Note that if the character you are searching for does not exist within the string you are searching or the the occurrence number you are searching for is greater than what exists in the string then this method will return -1.

提交回复
热议问题