Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ nth substr

//  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 :: retourner pointeur de type qstringlist qt 
Cpp :: how to sort a 2d array in c++ 
Cpp :: sfml mouse click 
Cpp :: how to load from files C++ 
Cpp :: c++ make constructor fails if bad argument 
Cpp :: how to set a string equal to another string cpp 
Cpp :: eosio get time 
Cpp :: exit() in c++ 
Cpp :: google test assert eq float 
Cpp :: c++ wait for user input 
Cpp :: stl for sorting in c++ 
Cpp :: cpp random in range 
Cpp :: c++ check open processes 
Cpp :: xmake set exe name 
Cpp :: copy substring to another string c++ 
Cpp :: cout.flush() in c++ 
Cpp :: equal_range in C++ 
Cpp :: convert string to stream c++ 
Cpp :: how to hide the c++ console 
Cpp :: read struct from file c++ 
Cpp :: tic toc toe c++ 
Cpp :: c++ code for insertion sort 
Cpp :: if even number c++ 
Cpp :: how to run a msi file raspbrain 
Cpp :: c++ find element in vector 
Cpp :: c++ call by value vs call by reference 
Cpp :: c++ return multiple values 
Cpp :: ue4 c++ enumaeration 
Cpp :: find max value in array c++ 
Cpp :: how to store pair in min heap in c++ 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =