Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to find nth occurence of a character in a string without using LINQ
Posted

Did you try anything?

It would be a simple for loop with an if. Something like:
C#
public int GetNthOccurenceIndex(string sample, char t, int nth)
{
    int count = 0;
    for (int i = 0; i < sample.Length; i++)
    {
        if (sample[i] == t)
        {
            count++;
            if (count == nth)
               return i;
        }
    }
    // -1 means nth occurrence was not found.
    return -1;
}
 
Share this answer
 
v2
MatchCollection mc = Regex.Matches(strList, c.ToString());
if (mc.Count >= numCount)
result = mc[numCount - 1].Index;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900