Unc*_*ens 16
你可以使用标准replace_if算法,除了谓词相当复杂(用当前的C++标准表示并且没有lambda).
你可以编写自己的,或者使用is_any_ofboost的字符串算法,所以:
#include <algorithm>
#include <string>
#include <boost/algorithm/string/classification.hpp>
#include <iostream>
int main()
{
std::string s("This,Is A|Test");
std::replace_if(s.begin(), s.end(), boost::is_any_of(", |"), '_');
std::cout << s << '\n';
}
Run Code Online (Sandbox Code Playgroud)
正如其他答案所示,您可以使用各种replace方法.但是,这些方法有多次扫描字符串的缺点(每个字符一次).如果您关心速度,我建议您推荐自己的替换方法:
void beautify(std::string &s) {
int i;
for (i = 0; i < s.length(); ++i) {
switch (s[i]) {
case ' ':
case ',':
case '|':
s[i] = '_';
}
}
}
Run Code Online (Sandbox Code Playgroud)