我这里有一些代码,其中,给定一个txt文件,其内容是
find replace pre
pre
cpre
,我想找到“预”的每个实例,和“k”追加到它。即:该文件应成为“找到替换KPRE”。
所以,我首先着手创建一个字符串,它是k和前的并置(假设k和前被ARGV [1]和argv [3],分别地)
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);
检查控制台上,附加=“KPRE”,这是正确的,但运行代码时,文件看起来像
find replace kkkkkkkkkkkkkkkk.....kkkkkkk
kkkkkkkkk......kkkkk
ckkkkk....kkkkk
第k去了一会儿,我无法看到滚动一路到右侧时前。我有困难,搞清楚为什么代码不会替换“KPRE”预'的情况下,即使在附加变量似乎是正确的。我有一种感觉它与我设置了1024个字符之间的温度的事实做,但即使如此,我不知道为什么K值是复制了很多次。
这里
while ((position = strstr(string, find)) != NULL) {
要传递给string
功能strstr()
。该strstr()
将指针返回find
在string
第一次出现。当你与pre
替换kpre
并再次调用strstr()
,它被重新调整指针pre
在string
第一次出现是replace
字符串的子字符串。 while
循环的一些迭代后,它将开始访问string
超出其大小,这将导致不确定的行为。
相反,通过向string
的strstr()
,你应该通过指针string
和以后每隔替换操作,字符串替换的部分后,使指针指向。另一种方式是,你可以通过使用字符指针,而不是使用strstr()
,这样遍历字符串的字符:
#define BUFSZ 1024
char* replace(char *string, const char *find, const char *replace) {
if ((string == NULL) || (find == NULL) || (replace == NULL)) {
printf ("Invalid argument..\n");
return NULL;
}
char temp[BUFSZ];
char *ptr = string;
size_t find_len = strlen(find);
size_t repl_len = strlen(replace);
while (ptr[0]) {
if (strncmp (ptr, find, find_len)) {
ptr++;
continue;
}
strcpy (temp, ptr + find_len); // No need to copy whole string to temp
snprintf (ptr, BUFSZ - (ptr - string), "%s%s", replace, temp);
ptr = ptr + repl_len;
}
return string;
}
请注意,上面的代码是基于例如,你在你的问题已经发布,并只给你如何可以实现自己的目标,而无需使用strstr()
的想法。在编写代码时,采取的其他可能性护理以及像,replace
是一个巨大的字符串。