So, in python, you can easily replace a phrase in a text using s.replace(,).
I wanted to know how to do the exact same thing on c++. the normal replace function does not do this.
string replace does a lot of different things.
do you have an example of what you want done?
I mean, here is a quick answer...
1 2 3
string s{"the quick brown fox jumped over a lazy dog"};
s.replace(s.find("brown fox"), string{"brown fox"}.length(), "pink panther");
cout << s << endl;
prints
the quick pink panther jumped over a lazy dog
** the length() call is just silliness, you know the length of a constant and don't need that fluff here.
Or to replace all occurrences rather than just the first:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
void replace(std::string& str, const std::string& old_substr, const std::string& new_substr)
{
for (size_t index {}; (index = str.find(old_substr), index) != std::string::npos; ++index)
str.replace(index, old_substr.length(), new_substr);
}
int main()
{
std::string s {"the quick brown fox jumped over a lazy dog brown fox jumped"};
replace(s, "brown fox", "pink panther");
std::cout << s << '\n';
}
the quick pink panther jumped over a lazy dog pink panther jumped