c - 递归 C 字符串替换

标签 c string recursion replace

我是 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/

相关文章:

c - 如何在局域网中只知道端口号就可以通过客户端程序获取服务器程序的ip?

python - 使用正则表达式删除字符串中最后一个数字之后的所有文本

javascript - 如何确保递归函数在返回之前不会再次被调用

C无限循环中的Collat​​z递归

算法:理解递归函数

c - (c cpp语言)

C 动画轮盘

c - 将字符串设置为 '\0'

c - 如何检查C字符串是否为空

c - 这段代码如何打印用户输入的最后一个词?