c++ - std::replace on std::string invalid operands to binary expression

标签 c++ string algorithm replace compiler-errors

我正在使用std::replace用另一个替换所有出现的字符串,所以这是我的代码:

static void escape(std::string& source,std::map<std::string, std::string> escape_map){
    for(auto&[from, to] : escape_map)
        std::replace(source.begin(), source.end(), from, to);
}
int main() {
    std::string s = "need to escape \" , \\ and \n .";
    std::cout<<s;
    escape(s, {
            {{"\n"}, {"\\n"}},
            {{"\\"}, {"\\\\"}},
            {{"\""}, {"\\\""}}
    });
}

但是当我编译时我得到
error: invalid operands to binary expression ('char' and 'const std::__1::basic_string<char>')
        if (*__first == __old_value)

最佳答案

如果我正确理解您的要求,那么您可以为此std::string::replace。将std::replace调用替换为

source.replace(source.find(from), from.length(), to);

请注意,如果要替换子字符串的多次出现,则必须在循环中调用replace。
auto f = source.find(from, 0);
while (f != std::string::npos)  // while sub-string can be replaced
{
  source.replace(f, from.length(), to);  // replace sub-string
  f = source.find(from, f); // search from position of replaced string
}

如果要从替换的字符串之后继续搜索,则需要在for循环的第二行
f = source.find(from, f + to.length()); 

如果您想使用更短的解决方案,则可以在同一条语句中使用以下方法进行多次替换:
source = std::regex_replace(source, std::regex{from}, to);

但请注意,重复构造std::regex会使速度变慢。

关于c++ - std::replace on std::string invalid operands to binary expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61036429/

相关文章:

c++ - eclipse 打开声明无法正常工作

c++ - OpenGL:将 Z 深度设置为统一与在顶点内冗余存储

javascript - 带有 "&lt;script&gt;"字符串的内联 javascript 错误地关闭了脚本标签

C语言,如何求二维数组中一个单词的长度?

java - 在java中读取String中的字符?

algorithm - 有什么比蛮力更好的算法来分离重叠类别中的项目?

c# - 以编程方式卸载掌上电脑程序

c++ - 调试和 Release模式下的不同结果

java - 遍历n维空间

performance - 如何在单个程序中检查我的两个不同进程的运行时间