开发者

What is the best way to replace inside a C++ string?

开发者 https://www.devze.com 2023-03-23 19:12 出处:网络
I\'m wondering what is the best and fastest way t开发者_如何学Pythono replace all occurences inside a string in c++?

I'm wondering what is the best and fastest way t开发者_如何学Pythono replace all occurences inside a string in c++?

Is there any way that does not require looping the replace function?


Checkout boost : boost::algorithm::replace_all and boost::algorithm::replace_all _copy

Still i don't know if it's faster than looping over the replace function. You'll have to make some tests.

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


You could try to use tr1 regular expression library. To be noted that I don't know if it's the best and fastest way so it might not be exactly what the OP asked for.

#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;
}

Regular expressions will also be available in the upcoming C++0X standard, so you would ditch the "tr1" from the namespace name when using a C++0X standard(part of standard compliant implementing the regex library for C++0X) compliant compiler.


There's replace_if in STL algorithms:

#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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消