I need help with creating a C# method that returns the index of the Nth occurrence of a character in a string.
For instance, the 3rd occurrence of the character 't'
in the string "dtststxtu"
is 5.
(Note that the string has 4 t
s.)
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.
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.
There is a minor bug in previous solution.
Here is some updated code:
s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With