我正在使用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/