I need help simplifying my function in this program. I was previously helped by
ID: 3621477 • Letter: I
Question
I need help simplifying my function in this program. I was previously helped by someone else and everything works great, however, I want it the function to be simpler because I am not the far ahead in my course. 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; <----- I have not went over this before, I have been explained
pos=in.find(change,0); on how it works, but I am not that far in my course.
while (pos !=in.npos) <----- Same thing here. I have not went over the npos
before either
{
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.