我是 C 编程的新手,过去只使用 C++ 和 String 类,但我想知道我将如何用另一个字符串递归替换一个字符串。
我的代码是这样的,但它似乎不能正常工作,而且我不能完全确定它在哪里失败。它在一个替换上工作正常,但在多个替换上它会失败。
#include <stdio.h>
#include <string.h>
char *replace_str(char *str, char *orig, char *rep)
{
int current_index = 0;
static char buffer[10000];
if (!strstr(str, orig)) // Is 'orig' even in 'str'?
{
return str;
}
while (1)
{
char *p;
if (!(p = strstr(str + current_index, orig))) // Is 'orig' even in 'str'?
{
return buffer;
}
strncpy(buffer, str, p-str); // Copy characters from 'str' start to 'orig' st$
buffer[p-str] = '\0';
sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
printf("%d -> %s\n", current_index, buffer);
current_index = (p - str) + strlen(rep);
str = buffer;
}
return buffer;
}
int main(void)
{
puts(replace_str("hello world world", "world", "world2"));
return 0;
}
在这个例子中,它打印了这个:
0 -> hello world2 world
12 -> hello world2 world22
hello world2 world22
最佳答案
它可能不是最好的实现,但是 here您会找到一个完成任务的 stringReplace 函数。
关于您的代码。首先,调用者最好提供其目标缓冲区,而不是将静态缓冲区放入函数中。然后,您不检查缓冲区溢出。
你的
strncpy(buffer, str, p-str); // Copy characters from 'str' start to 'orig' st$
将从 A 复制到 A 除了在第一次迭代中。这不好,缓冲区不应该重叠。请改用 memmove
。
但整个想法并不清晰,因为您更新用作源的同一缓冲区以捕获其他事件。
在某些时候,您覆盖输入(当 str 和 buffer 指向同一事物时)丢失信息,因为您的替换词比要替换的原始词长,因此您不保留“原始下一个字符”。 (如果您尝试使用“work”而不是“world2”,它应该可以工作)...
所以你的 current_index 应该索引原始字符串 str(你永远不会做 str = buffer),你将把你需要的部分追加到你的内部缓冲区(如果找到“world”,然后追加“world2”,将 current_index 更新为“world”的长度,然后继续)。
我会做(或多或少地尝试保持你的原创想法)
#include <stdio.h>
#include <string.h>
char *replace_str(char *str, const char *orig, const char *rep)
{
size_t buf_index = 0;
static char buffer[10000];
if (!strstr(str, orig)) // Is 'orig' even in 'str'?
{
return str;
}
buffer[0] = 0;
for(;;)
{
char *p;
if (!(p = strstr(str, orig)))
{
strcpy(buffer + buf_index, str);
return buffer;
}
strncpy(buffer + buf_index, str, p - str);
strcpy(buffer + buf_index + (p - str), rep);
buf_index += (p-str) + strlen(rep);
str = p + strlen(orig);
}
return buffer;
}
int main(void)
{
puts(replace_str("hello world world world", "wor", "world2"));
return 0;
}
关于c - 递归 C 字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6557476/