Didn't want to mess up earlier post. This is my final code and I solved the 2nd step too.
Code:
int main() {
char str1[100];
char str2[100];
char str3[100];
printf("Enter a sentence: ");
fgets(str1, 100, stdin);
printf("Enter a string you want to change: ");
fgets(str2, 100, stdin);
printf("New string: ");
fgets(str3, 100, stdin);
*(strchr(str1, '\n')) = '\0';
*(strchr(str2, '\n')) = '\0';
*(strchr(str3, '\n')) = '\0';
int i;
for(i = 0; str2[i] != '\0'; i++){}
char *p = strstr(str1, str2);
strncpy(p, str3, i);
while( p != NULL ) {
p = strstr(p+1, str2);
if( p != NULL )
strncpy(p, str3, i);
}
puts(str1);
return 0;
}
Example:
aaa bbb aaa.aaa.aaa.
aaa
xxx
prints: xxx bbb xxx.xxx.xxx.
Now we came to the last part. I explained this before this post. I want 2nd and 3rd string to have different number of characters.
Example:
aaa bbb aaa.aaa.aaa.
aaa
R
prints: R bbb R.R.R.
I cannot think a solution for this since it will change other characters' index as well as addresses. Need a hand here