在C ++中替换子字符串不区分大小写

时间:2016-11-13 18:33:20

标签: c++ string

我需要替换字符串中的子字符串。例如:

输入:

  

始终

     

从不

     

我会一直跑。 ALWAYS!

输出:

  

我永远不会跑。 NEVER!

replacefind工作正常。但是,问题是区分大小写。我有这个简单的功能,但这是不完整的。

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

   return s;
}

如何使搜索过程不区分大小写?

3 个答案:

答案 0 :(得分:2)

将原始字符串和搜索短语都转换为小写,然后搜索:

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;
}

注意:

  1. 您必须保留原始s,因为您需要在不更改其情况的情况下将其退回。
  2. 您可以直接更改a的大小写,因为您不再使用它了。
  3. 您不需要更改b的大小写,因为您根本没有使用它进行搜索。

答案 1 :(得分:2)

使用c ++ 11,试试这样:

string subTag(string s,string a, string b)
{
    auto pos = std::search(s.begin(), s.end(), a.begin(), a.end(), [](const char c1, const char c2){ return (std::tolower(c1)) == (std::tolower(c2));});
    if(pos == s.end())
        return "";
    auto pos2 = pos;
    std::cout << *pos << std::endl;
    std::advance(pos2, a.size());
    s.replace(pos, pos2, b);

   return s;
}

答案 2 :(得分:0)

If you want to replace all substrings, consider the following algorithm.

It avoids infinite loops for calls like "subTag( "T_T", "t", "ttt" );"

std::string subTag( std::string s, std::string a, const std::string& b )
{
    if( a.empty() )
        return s;

    std::string res = s;
    std::transform( s.begin(), s.end(), s.begin(), ::tolower );
    std::transform( a.begin(), a.end(), a.begin(), ::tolower );

    size_t pos = s.rfind( a );
    while( pos != std::string::npos )
    {
        res.replace( res.begin() + pos, res.begin() + pos + a.length(), b );

        if( pos == 0 )
            return res;

        pos = s.rfind( a, pos - 1 );
    }

    return res;
}
相关问题