Horje
c++ index of nth occurence Code Example
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;
}




Cpp

Related
suppress individual warnings in visual c++ Code Example suppress individual warnings in visual c++ Code Example
C++ sqlite open file in other directory Code Example C++ sqlite open file in other directory Code Example
ifstream relative file path Code Example ifstream relative file path Code Example
ue4 find component c++ Code Example ue4 find component c++ Code Example
__lg(x) in c++ Code Example __lg(x) in c++ Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
10