I need help simplifying my function in this program. I was previously helped by
ID: 3621453 • Letter: I
Question
I need help simplifying my function in this program. I was previously helped by someone else and everything works great, I just don't understand how the function works since I have not gotten that far in my book. I will post the code, and the question again.Write a function named replaceSubstring. The function should accept three C-string or string object arguments. Let's call them string1, string2, and string3. It should search for string1 for all occurences of string2. When it finds an occurence of string2, it should replace it with string3. For example, suppose the three arguments have the following values:
string1: "the dog jumped over the fence"
string2: "the"
string3: "that"
With these three arguments, the function would return a string object with the value "that dog jumped over that fence." Demonstrate the function in a complete program.
#include<iostream>
#include <string>
using namespace std;
void replaceSubstring(string &,string,string);
int main()
{
string string1;
string string2;
string string3;
string1 = "the dog jumped over the fence";
string2 = "the";
string3 = "that";
replaceSubstring(string1, string2, string3);
cout<<string1<<endl;
return 0;
}
void replaceSubstring(string &in ,string change,string to)
{
string::size_type pos;
pos=in.find(change,0);
while (pos !=in.npos)
{
in.erase(pos,change.length());
in.insert(pos,to);
pos=in.find(change,pos+1);
}
return;
}
Explanation / Answer
std::string replaceSubstring(const std::string& string1,const std::string& string2,const std::string& string3) { std::string newString; for (size_t i=0;iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.