Implement "search and replace" for null-terminated strings. - C++ Data Type

C++ examples for Data Type:char array

Description

Implement "search and replace" for null-terminated strings.

Demo Code

#include <iostream>
#include <cstring>
using namespace std;
bool search_and_replace(char *orgstr, int maxlen, const char *oldsubstr, const char *newsubstr);
int main() {/*from w w  w .java  2 s.c om*/
   char str[80] = "alpha beta gamma alpha beta gamma";
   cout << "Original string: " << str << "\n\n";
   cout << "First, replace all instances of alpha with epsilon.\n";
   
   // Replace all occurrences of alpha with epsilon.
   while(search_and_replace(str, 79, "alpha", "epsilon"))
      cout << "After a replacement: " << str << endl;
   cout << "\nNext, replace all instances of gamma with zeta.\n";
   
   // Replace all occurrences of gamma with zeta.
   while(search_and_replace(str, 79, "gamma", "zeta"))
      cout << "After a replacement: " << str << endl;
   cout << "\nFinally, remove all occurrences of beta.\n";
   
   while(search_and_replace(str, 79, "beta", ""))
      cout << "After a replacement: " << str << endl;
   return 0;
}
bool search_and_replace(char *str, int maxlen,  const char *oldsubstr, const char *newsubstr) {
   if(!*oldsubstr)
      return false;
   
   int len = strlen(str) - strlen(oldsubstr) + strlen(newsubstr);
   
   if(len > maxlen) return false;
   
   char *p = strstr(str, oldsubstr);
   
   if(p) {
      memmove(p+strlen(newsubstr), p+strlen(oldsubstr),  strlen(p)-strlen(oldsubstr)+1);
      strncpy(p, newsubstr, strlen(newsubstr));
      return true;
   }
   return false;
}

Result


Related Tutorials