Answer:
All is in explanation.
Explanation:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
//function prototype
string replaceSubstring(const char *, const char *, const char*);
string replaceSubstring(string, string, string);
int main()
{
//declare three char array to hold strings of max 100 chars
char string1[101];
char string2[101];
char string3[101];
//prompt user to enter input
//then read
cout << "Enter string to search:\n";
cin.getline(string1, 101);
cout << "Enter the string you want to replace:\n";
cin.getline(string2, 101);
cout << "What do you want to replace it with?\n";
cin.getline(string3, 101);
cout << "Your updated string is:\n";
cout << replaceSubstring(string1, string2, string3);
//return 0 to mark successful termination
return 0;
}
string replaceSubstring(const char *st1, const char *st2, const char *st3){
//declare pointers start and occurrence
//initialize start with string to search
//char *startSearch = st1;
//initialize occurrence with the first occurrence
//of st2 in st1
char *occurrence = strstr(st1, st2);
//declare empty string
string output = "";
//using occurrence as control for while loop
//means that it will iterate until no more
//occurrences are found
while(occurrence){
//append to final string the characters of st1
//up until first occurrence of st2
output.append(st1, (occurrence-st1));
//append st3 to final string
output.append(st3, strlen(st3));
//update occurrence to point to character
//of st1 just after first occurrence of st2
st1 = st1 + (occurrence-st1) + strlen(st2);
//find new occurrence
occurrence = strstr(st1, st2);
}
//st1 now points to first character after
//last occurrence of st2
output.append(st1, strlen(st1));
return output;
}
string replaceSubstring(string st1, string st2, string st3){
//convert input strings to C-strings
const char *ptr1 = st1.c_str();
const char *ptr2 = st2.c_str();
const char *ptr3 = st3.c_str();
//call function that accepts C-strings
replaceSubstring(ptr1, ptr2, ptr3);
}