c++ replace n substrings

C++
using namespace std;

string ReplaceAllSubstringOccurrences(string sAll, string sStringToRemove, string sStringToInsert)
{
   int iLength = sStringToRemove.length();
   size_t index = 0;
   while (true)
   {
      /* Locate the substring to replace. */
      index = sAll.find(sStringToRemove, index);
      if (index == std::string::npos)
         break;

      /* Make the replacement. */
      sAll.replace(index, iLength, sStringToInsert);

      /* Advance index forward so the next iteration doesn't pick it up as well. */
      index += iLength;
   }
   return sAll;
}


// EXAMPLE: in usage
string sInitialString = "Replace this, and also this, don't forget this too";
string sFinalString = ReplaceAllSubstringOccurrences(sInitialString, "this", "{new word/phrase}");
cout << "[sInitialString->" << sInitialString << "]\n";
cout << "[sFinalString->" << sFinalString << "]\n";

/* OUTPUT:
[sInitialString->Replace this, and also this, don't forget this too]
[sFinalString->Replace {new word/phrase}, and also {new word/phrase}, don't forget {new word/phrase} too] 
*/
string ReplaceFirstNSubstringOccurrences(string sAll, string sStringToRemove, string sStringToInsert, int iN)
{
   // get the length
   int iLength = sStringToRemove.length();
   size_t index = 0;
   int counter = 1;
   while (counter <= iN)
   {
      // Locate the substring to replace.
      index = sAll.find(sStringToRemove, index);
      if (index == std::string::npos)
         break;

      // Make the replacement.
      sAll.replace(index, iLength, sStringToInsert);

      // Advance index forward so the next iteration doesn't pick it up as well.
      index += iLength;
      counter++;
   }
   return sAll;
}


// EXAMPLE: in usage
string sInitialString = "Replace this, and also this, but not this at the end";
string sFinalString = ReplaceFirstNSubstringOccurrences(sInitialString, "this", "{new}",2);
cout << "[sInitialString->" << sInitialString << "]\n";
cout << "[sFinalString->" << sFinalString << "]\n";

/* OUTPUT:
[sInitialString->Replace this, and also this, but not this at the end]
[sFinalString->Replace {new}, and also {new}, but not this at the end]
*/


Source

Also in C++: