I think you said it wrong. replace string 3, that, with str2, the, in str1 (does not contain).
There is no easy way. Its going to be hands on and its going to depend on how str1 is defined.
lets kill the first the and assume you want to replace the with that.
dog jumped over the fence
becomes
dog jumped over that fence
lets see what we can do … give me a few min, but you are going to need at least
-strstr
-memcpy
-strlen
Here is an incomplete starting example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int main()
{
char str1[100] = "dog jumped over the fence"; //the way I made this string is important.... I gave lots of extra room, and it can be edited.
char str2[] = "the";
char str3[] = "that";
int offset = strlen(str3)-strlen(str2); //how much do we need to shift the string?
char * ss;
ss = strstr(str1, str2); //is the target even in there, and if so, you need to loop
//to do it until it is no longer there (assuming the replace != the original too,
//may need to check that)
if(ss) //found it. c++ borked this. null = 0 = false. strstr rocks ;)
{
if(offset >0) //you need more cases, what if this is 0, what if is negative?
//but if its positive shift the data to make room for the extra letters
memmove(ss+strlen(str2)+offset, ss+strlen(str2), strlen(str1));
//the strlen str1 is me being lazy you can find the exact amount if you want.
memcpy(ss,str3, strlen(str3));
}
cout << str1 << endl;
}
|
**memmove is able to do memcpy inside the same buffer, memcpy may not do this safely, I bugged that up the first time.
here is a C program to do it
https://www.geeksforgeeks.org/c-program-replace-word-text-another-given-word/
but honestly I think it may be a little overdone due to using dynamic memory for some unholy reason.
hands-on C string stuff takes getting used to. Let us know if you need more, but that should get you a long way towards getting it done.