C++字符替换

tin*_*ime 8 c++ regex string boost

替换字符串中字符的最佳方法是什么?

特别:

"This,Is A|Test" ----> "This_Is_A_Test"
Run Code Online (Sandbox Code Playgroud)

我想替换所有逗号,空格和"|" 带有下划线.

(我可以访问Boost.)

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)


Bjö*_*lex 11

您可以使用STL算法replace_if.


not*_*oop 9

正如其他答案所示,您可以使用各种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)