I have some code here where, given a .txt file whose contents is
find replace pre pre cpre ,I want to find every instance of "pre", and append "k" to it. ie the file should become "find replace kpre".
So I first set out to create a string that is the concatenation of k and pre (assume k and pre are argv[1] and argv[3], respectively)
char appended[1024]; strcpy(appended, argv[1]); strcat(appended, argv[3]); printf("appended string is %s", appended); //prints kpre, which is good char *replaced = replace(buf, argv[3], appended); //*string is a line in the file char* replace(char *string, char *find, char *replace) { char *position; char temp[1024]; int find_length = strlen(find); int index = 0; while ((position = strstr(string, find)) != NULL) { strcpy(temp, string); index = position - string; string[index] = '\0'; strcat(string, replace); //add new word to the string strcat(string, temp + index + find_length); //add the unsearched //remainder of the string } return string; } ................. fputs(replaced, temp); Checking on the console, appended = "kpre", which is correct, but when the code is run the file looks like
find replace kkkkkkkkkkkkkkkk.....kkkkkkk kkkkkkkkk......kkkkk ckkkkk....kkkkk the k's go on for a while, I cannot see pre when scrolling all the way to the right. I'm having difficulty figuring out why the code doesn't replace the instance of 'pre' with 'kpre', even when the appended variable appears to be correct. I have a feeling it has to do with the fact that I set a 1024 character for temp, but even then I'm not sure why k was copied so many times.
"pre", replace all instances of"pre"with"kpre". Ok. That give me "kpre". Now, starting from the beginning of the string, repeat that. Um... if you start searching for"pre"from the beginning of the string you're going to find one for sure, because you just wrote one. So, the next result would be"kkpre", then"kkkpre", then"kkkkpre"etc. . See the problem? You have to move where you search from to not include the text you just replaced. A pointer would really be ideal for that, btw.strstr) know that this "index" variable exists, much less what its value is?replaceis longer thanfindandfindisn't the last word instring?