Gustavo Marini Gustavo Marini - 27 days ago 9
C++ Question

Replace substring case insensitive in C++

I need to replace a substring in a string. For example:

Input:


Always

Never

I will always run. ALWAYS!


Output:


I will never run. NEVER!


replace
and
find
work fine. However, the problem is the case sensitive. I have this simple function to do that, but this is incomplete.

string subTag(string s,string a,string b)
{
while(s.find(a)!=-1){
s.replace(s.find(a), a.size(), b);
}

return s;
}


How can I make the search process case insensitive?

Answer

Convert both the original string the search phrase to lower than search:

string subTag(string s,string a,string b){
   std::string lower_s;
   std::transform(s.begin(), s.end(), lower_s.begin(), ::tolower);
   std::transform(a.begin(), a.end(), a.begin(), ::tolower);
   auto position=lower_s.find(a);
   while(position!=std::string:npos){
        s.replace(position, a.size(), b);
        position=lower_s.find(a);
   }
   return s;
}

Notes:

  1. You have to keep the original s since you need to return it without changing its case.
  2. You can change the case of a directly since you are not using it anymore.
  3. you do not need to change the case of b since you are not using it to search at all.