Search
 
SCRIPT & CODE EXAMPLE
 

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;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: how to sort a 2d array in c++ 
Cpp :: ue4 find component c++ 
Cpp :: file handling 
Cpp :: change const value c++ 
Cpp :: screen record ios simulator 
Cpp :: cuda kernel extern shared memory 
Cpp :: how to make a sqlite3 object in cpp 
Cpp :: c++ remove last element from vector 
Cpp :: hi cpp 
Cpp :: c++ nodiscard 
Cpp :: differency between c++ std and stl 
Cpp :: c++ randomization 
Cpp :: capacity() in c++ 
Cpp :: Array implementation of Queue using class in c++ 
Cpp :: c++ random number generator uniform distribution 
Cpp :: create n threads cpp 
Cpp :: std string to const char * c++ 
Cpp :: how to get double y dividing 2 integers in c++ 
Cpp :: spicoli 
Cpp :: 2d array using vector 
Cpp :: array 2d dynamic allocation c++ 
Cpp :: c++ code for selection sort 
Cpp :: c++ infinite for loop 
Cpp :: vector to string c++ 
Cpp :: latex double subscript 
Cpp :: c++ type casting 
Cpp :: c++ pointer null vs nullptr 
Cpp :: height of bst cpp 
Cpp :: all data types in c++ 
Cpp :: C++ press enter to continue function 
ADD CONTENT
Topic
Content
Source link
Name
6+7 =