Replacing a string in char array

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 #include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
const int N=50;

int main ()
{
	char str[N],str2[N],str3[N],tail[N];
	char *opstring;

	unsigned int 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;
}
1
2
3
4
5
6
	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 
How could I omitt that. It solved my problem entirely. I appreciate your efforts to read this, thank you.
Topic archived. No new replies allowed.