Cpp - Write program to create string and do insert, erase and replace

Requirements

Write a C++ program to

  • initialize a string s1 with the string "this is a test by ..."and a second string s2 with the string "goes",
  • insert string s2 in front of "by" in string s1,
  • erase the remainder of string s1 after the substring "by",
  • replace the substring "time" in s1 with "book2s.com".

Output string s1 on screen at the beginning of the program and after every modification.

Demo

#include <iostream> 
#include <string> 
using namespace std; 


int main() /*from w ww.j av  a 2  s.  c o m*/
{ 

   string s1 = "this is a test by ...", s2 = "goes "; 
        
   int pos = 0; 

   cout << "s1 : " << s1 << endl; 

   // To insert: 
   cout << "\nInserting in string \"" << s2 <<"\""<< endl; 

   pos = s1.find("by"); 
   if( pos != string::npos ) 
       s1.insert(pos,s2); 
   cout << "s1 : " << s1 << endl;              // Result 

   // To erase: 
   cout << "\nTo erase remaining characters behind \"by\":" 
         << endl; 

   pos = s1.find("by"); 
   if( pos != string::npos ) 
       s1.erase(pos + 3); 
   cout << "s1 : " << s1 << endl;              // Result 

   // To replace: 
   cout << "\nTo replace \"time\" by \"book2s.com\":" 
         << endl; 

   pos = s1.find("time"); 
   if( pos != string::npos ) 
       s1.replace(pos, 4, "book2s.com"); 
   cout << "s1 : " << s1 << endl;             // Result 
   return 0; 
}

Result