Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Nth occurrence of a character in a string

Tags:

string

c#

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 ts.)

like image 972
jozi Avatar asked Apr 03 '10 15:04

jozi


People also ask

How do you find the nth occurrence 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.


2 Answers

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.

like image 95
Mike Two Avatar answered Sep 30 '22 11:09

Mike Two


There is a minor bug in previous solution.

Here is some updated code:

s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count(); 
like image 33
shalin shah Avatar answered Sep 30 '22 09:09

shalin shah