Answers for "statement that replace a substring with another string in c++"

C++
2

c++ replace substrings

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] 
*/
Posted by: Guest on June-02-2020
0

how to replace part of string with new string c++

//String Replacement
#include <string>

int main(){
  //String before replacement
  string str = "We want to replace all of you";
  //use this inbuilt function
  str.replace(19,10,"me");
    
  cout<<str;
   
  return 0;
}
Posted by: Guest on October-08-2021

Code answers related to "statement that replace a substring with another string in c++"

Browse Popular Code Answers by Language