I'm working on a function that accepts 3 C-strings and my objective is to replace the word that the user finds anywhere on the sentence with the one he/she inputs.
Below is the code of my function:
void replaceSubstring(char str1[], char str2[], char str3[])
{
char *a= new char(sizeof(str1));
char *b= new char(sizeof(str1));
int len=0;
for(unsigned int ind= 0; ind< sizeof(str1); ind++)
{
for(unsigned ind1= 0; ind1< sizeof(str2); ind1++)
a[ind]= str1[ind+ ind1];
a[ind]= '\0';
if(strcmp(str1, str2))
{
for(unsigned int y= 0; y< sizeof(str3); y++)
{
b[len]= str3[y];
len++;
}
ind+= (sizeof(str2)- 1);
}
else
{
cout<< "Error! No match found!"<< endl;
}
}
cout<< b<< endl;
}
Let us show an example of my output:
Enter a string: I love mangoes
Enter the word you want to look for: mangoes
Enter the new word to replace "mangoes" with: cheese
Output? chee─
Can anyone explain what can I do to improve this and why this is causing a glitch? Any info is truly appreciated.
P.S: I've tried working with strstr, but strstr returns the pointer and leaves the sentence cut off and then I get worried figuring out a way to skip characters from the end of the sentence to where the word is and figuring out what to do afterwards. How could I do this using strstr, if possible, without cutting the sentence?
Thank you very much for your help.