Reputation: 93
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
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
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.
Upvotes: 1
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