递归C字符串替换

Tom*_*ese 3 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;
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,它打印出这个:

 0 -> hello world2 world
12 -> hello world2 world22
hello world2 world22
Run Code Online (Sandbox Code Playgroud)

Shi*_*zou 5

它可能不是最好的实现,但在这里你找到一个执行任务的stringReplace函数.

关于你的代码.首先,调用者提供其dest缓冲区而不是在函数中使用静态缓冲区更好.然后,您不检查缓冲区溢出.

您的

    strncpy(buffer, str, p-str); // Copy characters from 'str' start to 'orig' st$
Run Code Online (Sandbox Code Playgroud)

除了第一次迭代外,它将从A复制到A.这不好,缓冲区不应该重叠.请memmove改用.

但是整个想法并不干净,因为您更新了用作源的相同缓冲区以捕获其他事件.

在某些时候,你覆盖输入(当str和缓冲区指向相同的东西时)丢失信息,因为你的替换单词比要替换的原始单词长,所以你不保留"原始的下一个字符".(如果您尝试使用"work"而不是"world2",它应该可以工作)...

所以你的current_index应该索引原始的字符串str(并且你永远不会做str = buffer),你将把你需要的部分附加到你的内部缓冲区(如果找到则发生"world",然后追加"world2",按"世界"的长度更新current_index并继续).

我愿意(试图保持原创的想法,或多或少)

#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;
}
Run Code Online (Sandbox Code Playgroud)