Hello. I need to write a program which replaces a string within a char array. However, there are some boundaries I have to obey. First of all I can't use string class, it has to be a char array. Second, the string in which changes are to be made, the string which has to be replaced and the string which has to be put into the string have to be entered by the user. Third, I can't use such functions as replace or memmove. I've read about them and I noticed that they might be useful but I am supposed to do this without them.
Here is my algorithm. Find the string which has to be replaced in the main string with strstr function. Then save the characters after the string you need to replace to another string (tail). Copy the string that has to replace the older one and finally add the tail to the end of the main string.
Example input:
This is difficult program.
is difficult
was not that hard
Output:
This was not that hard program.
#include <iostream>
#include <cstring>
#include <cctype>
usingnamespace std;
constint N=50;
int main ()
{
char str[N],str2[N],str3[N],tail[N];
char *opstring;
unsignedint i,j=0,str2position;
cout << "Enter the first string: \n";
cin.getline(str,N);
cout << "Enter the string that has to be replaced: \n";
cin.getline(str2,N);
cout <<"Enter the string to replace the previous string: \n";
cin.getline(str3,N);
opstring=strstr(str,str2);//searching for the string we need to replace
str2position=(int)(opstring-str);//saving position of the string we need to replace
for (i=str2position+strlen(str2);i<=strlen(str)-1;i++) //copying rest of the first string to a separate array
{
tail[j]=str[i];
j++;
}
strcpy(opstring,str3);//replacing string with a new one
strcat(str,tail);//adding rest of the string to the main string
cout <<str <<endl;
return 0;
}
for (i = str2position + strlen(str2); i <= strlen(str) - 1; i++) //copying rest of the first string to a separate array
{
tail[j] = str[i];
j++;
}
tail[j] = '\0'; //add this