此问题已经在这里有了答案:
替换功能允许从一个字符串中更改另一个字符。使用:replace(s.begin(),s.end(),'X','Y');但是可以用一个改变2个或更多不同的字符吗?例如:在字符串“告诉我们更多有关您的问题”中,我想将所有“ o,i,u”更改为“ x”。因此在输出处将是:告诉xs abxxt yxxr qxuestixn
从另一个答案开始,它应该起作用:
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}