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

C++ examples for STL:string

Description

Implement case-insensitive search and search-and-replace for string objects.

Demo Code

#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
bool comp_ign_case(char x, char y);
string::iterator search_ign_case(string &str, const string &substr);
bool search_and_replace_ign_case(string &str, const string &oldsubstr, const string &newsubstr);
int main()/*from w  w  w . j  ava 2s .  com*/
{
   string strA("This is a test of case-insensitive searching.");
   string strB("test");
   string strC("TEST");
   string strD("testing");
   cout << "First, demonstrate search_ign_case().\n";
   cout << "String to be searched:\n" << strA << "\n\n";
   cout << "Searching for " << strB << ". ";
   if(search_ign_case(strA, strB) != strA.end())
      cout << "Found!\n";
   cout << "Searching for " << strC << ". ";
   if(search_ign_case(strA, strC) != strA.end())
      cout << "Found!\n";
   cout << "Searching for " << strD << ". ";
   if(search_ign_case(strA, strD) != strA.end())
      cout << "Found!\n";
   else
      cout << "Not Found.\n";
   cout << "\nRemainder of string after finding 'of':\n";
   string::iterator itr = search_ign_case(strA, "of");
   while(itr != strA.end())
         cout << *itr++;
   cout << "\n\n";

   strA = "Alpha Beta Gamma alpha beta gamma";
   cout << "search_and_replace_ign_case().\n";
   cout << "String that will receive replacements:\n" << strA << "\n\n";
   cout << "Replacing all occurrences of alpha with zeta:\n";
   while(search_and_replace_ign_case(strA, "alpha", "zeta"))
         cout << strA << endl;
   return 0;
}
string::iterator search_ign_case(string &str, const string &substr) {
      return search(str.begin(), str.end(), substr.begin(), substr.end(), comp_ign_case);
}
bool comp_ign_case(char x, char y) {
      return tolower(x) == tolower(y);
}
bool search_and_replace_ign_case(string &str, const string &oldsubstr, const string &newsubstr) {
      string::iterator startitr;
      startitr = search_ign_case(str, oldsubstr);
      if(startitr != str.end()) {
         str.replace(startitr, startitr+oldsubstr.size(), newsubstr);
         return true;
      }
      return false;
}

Result


Related Tutorials