Implement search-and-replace for string objects. - C++ STL

C++ examples for STL:string

Description

Implement search-and-replace for string objects.

Demo Code

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

bool search_and_replace(string &str, const string &oldsubstr, const string &newsubstr);

int main()/*ww  w  .  ja  v a 2  s .  c  o  m*/
{
   string str = "This is a test. So is this. this is a test (^*(^* ^*^*&^ 67978";
   cout << "Original string: " << str << "\n\n";
   cout << "Replacing 'is' with 'was':\n";

   while(search_and_replace(str, "is", "was"))
      cout << str << endl;
   cout << endl;

   string oldstr("So");

   string newstr("So too");
   cout << "Replace 'So' with 'So too'" << endl;
   search_and_replace(str, oldstr, newstr);
   cout << str << endl;
   return 0;
}
bool search_and_replace(string &str, const string &oldsubstr, const string &newsubstr) {
   string::size_type startidx;
   startidx = str.find(oldsubstr);
   if(startidx != string::npos) {
      str.replace(startidx, oldsubstr.size(), newsubstr);
      return true;
   }
   return false;
}

Result


Related Tutorials