replace function with c++

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.
Last edited on
Just iterating off jonnin's post, perhaps you might want something more generalized.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Example program
#include <iostream>
#include <string>
using namespace std;

void replace(string& str, const string& old_substr, const string& new_substr)
{
    size_t index = str.find(old_substr);
    if (index != std::string::npos)
    {
        str.replace(index, old_substr.length(), new_substr);   
    }
}

int main()
{
    string s{"the quick brown fox jumped over a lazy dog"};
    replace(s, "brown fox", "pink panther");

    cout << s << endl;
}
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

Last edited on
Topic archived. No new replies allowed.