Advertisement
rufwork

NthIndexOfCharInString

Oct 11th, 2012
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.44 KB | None | 0 0
  1. // from http://stackoverflow.com/a/6004505/1028230, edited from count to place of nth count.
  2. public static int NthIndexOfCharInString(string strHaystack, char charNeedle, int intOccurrenceToFind)
  3. {
  4.     int intReturn = -1;
  5.  
  6.     int count = 0;
  7.     int n = 0;
  8.  
  9.     while ((n = strHaystack.IndexOf(charNeedle, n)) != -1 && count < intOccurrenceToFind)
  10.     {
  11.         n++;
  12.         count++;
  13.     }
  14.  
  15.     if (count == intOccurrenceToFind) intReturn = n;
  16.  
  17.     return intReturn;
  18. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement