public
Created

Another way to loop

  • Download Gist
alternative-looping.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// Alternative looping.
// I wouldn't do this using a foreach loop, but it is much nicer than
// the original here: http://stackoverflow.com/a/11367974/707111
 
public int getNthIndex(string str, char c, int n)
{
int index = 0;
int count = 0;
 
if(n == 0)
return -1;
 
foreach(char i in str)
{
if (i == c) {
count++;
 
if (count == n)
return index;
}
 
index++;
}
 
return -1;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.