Greta
Greta

Reputation: 93

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

I'm wondering what is the best and fastest way to replace all occurences inside a string in c++?

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

Upvotes: 1

Views: 947

Answers (3)

celavek
celavek

Reputation: 5705

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.

Upvotes: 1

Guillaume Thomas
Guillaume Thomas

Reputation: 2310

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

Upvotes: 1

Antti
Antti

Reputation: 12479

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

Upvotes: 0

Related Questions