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

时间:2011-07-30 08:09:07

标签: c++ replace

我想知道在c ++中用字符串替换所有出现的最好和最快的方法是什么?

有没有办法不需要循环替换功能?

3 个答案:

答案 0 :(得分:1)

Checkout boost:boost :: algorithm :: replace_all和boost :: algorithm :: replace_all _copy

我仍然不知道它是否比循环替换功能更快。你必须做一些测试。

http://www.boost.org/doc/libs/1_47_0/doc/html/string_algo/reference.html#header.boost.algorithm.string.replace_hpp

答案 1 :(得分:1)

您可以尝试使用tr1正则表达式库。需要注意的是,我不知道它是否是最好和最快的方式,所以它可能不是OP所要求的。

#include <iostream>
#include <regex>
#include <string>

int main()
{
        std::string str = "Hello Earth from Mars! Mars salutes Earth!";
        std::tr1::regex rx("Mars");
        std::string str2 = std::tr1::regex_replace(str, rx, std::string("Saturn"));

        std::cout << str2 << endl;

        return 0;
}

正式表达式也将在即将推出的C ++ 0X标准中提供,因此当使用C ++ 0X标准时,您将从命名空间名称中删除“tr1”(标准兼容部分实现C +的正则表达式库) + 0X)兼容编译器。

答案 2 :(得分:0)

STL算法中有replace_if:

#include <string>
#include <iostream>
#include <algorithm>

bool is_f(char c)
{
    return c == 't';
}

int main(void)
{
        std::string s = "this is a test string";
        std::replace_if(s.begin(), s.end(), is_f, 'd');
        std::cout << s << std::endl;
        return 0;
}