I need help with the following program. I don't know how to check if occurrences of string2 are inside string1, and then replace them with string3.
Write a function named
replaceSubstring. The function should accept three string object arguments. Let’s call themstring1, string2, and string3. It should searchstring1for all occurrences ofstring2. When it finds an occurrence ofstring2, it should replace it withstring3. Demonstrate and test the function with a complete program.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.
int main()
{
string string1 = "xyzxyzxyz";
string string2 = "xyz";
string string3 = "a";
replaceSubstring(string1, string2, string3);
return 0;
}
void replaceSubstring(string string1, string string2, string string3)
{
string result;
for (int i = 0; i < string1.length(); i++){
if (string1.find(string2, i)){
result = string1.replace(i, string3.length()+i, string3);
}
}
cout << result;
}