gpt4 book ai didi

代码似乎无法正确打印连接的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:06 25 4
gpt4 key购买 nike

我这里有一些代码,给定一个内容为 .txt 的文件

find replace pre
pre
cpre

,我想找到“pre”的每个实例,并在其后附加“k”。即文件应该变成“查找替换kpre”。

所以我首先着手创建一个字符串,它是 k 和 pre 的串联(假设k和pre分别是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);

在控制台上检查,appended = "kpre",这是正确的,但是当代码运行时文件看起来像

find replace kkkkkkkkkkkkkkkk.....kkkkkkk
kkkkkkkkk......kkkkk
ckkkkk....kkkkk

k 持续了一段时间,一直向右滚动时我看不到 pre。我很难弄清楚为什么代码没有被替换'pre' 和 'kpre' 的实例,即使附加的变量看起来是正确的。我感觉这与我为 temp 设置了 1024 个字符有关,但即便如此我也不确定为什么 k 被复制了这么多次。

最佳答案

这里

    while ((position = strstr(string, find)) != NULL) {

你正在通过 stringstrstr()功能。 strstr()将返回指向第一次出现的 find 的指针在 string .当您更换 prekpre再次调用strstr() , 它正在重新调整指向第一次出现的 pre 的指针在 string这是 replace 的子串字符串。在 while 的一些迭代之后循环,它将开始访问 string超出其大小将导致未定义的行为。

而不是传递 stringstrstr() ,您应该将指针传递给 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是一个巨大的字符串。

关于代码似乎无法正确打印连接的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com