Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

c++ index of nth occurence

//  Gets the nth occurrence of the substring within the string
int GetIndexOfNthOccurrenceInString(string sMain,string sSubstr, int iN)
{
   int iIndex = -1;
   size_t stIndex = 0;

   switch (iN)
   {
      case -1: // User wants the very last occurrence of sSubstr
         stIndex = sMain.rfind(sSubstr);
         if (stIndex == string::npos)
         {
            return -1;
         }

         return int(stIndex);

      case 0: // provide for if the user asks for the 0th occurrence (make this the first occurence)
         iN = 1;
         break;
   }

   int iCurOccurrence = 0;

   while ( (iCurOccurrence != iN) && (iCurOccurrence < sMain.size()) )
   {
      stIndex++;
      stIndex = sMain.find(sSubstr, stIndex);
      if (stIndex == string::npos)
      {
         return -1;
      }
      iCurOccurrence++;
      iIndex = int(stIndex);
   }

   int iPos = int(stIndex);
   return iIndex;
}
 
PREVIOUS NEXT
Tagged: #index #nth #occurence
ADD COMMENT
Topic
Name
4+4 =