【发布时间】:2011-09-27 07:12:15
【问题描述】:
我是 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
【问题讨论】:
-
“失败”是什么意思?是停止替换还是出现错误?
-
我说的不是“递归”而是“迭代”。循环直到你找不到搜索字符串。
-
它失败了,因为它不再正确替换。这是示例输出:0 -> hello world2 world 12 -> hello world2 world22 hello world2 world22
-
递归函数中的静态缓冲区向我发出警告标志。您可以管理的字符串长度有一个未经检查的上限,这意味着该函数的所有嵌套调用都使用相同的存储。这也意味着没有线程安全。这不一定是错的。但这对我来说是一个危险信号。
标签: c string recursion replace