c - 查找替换子串C

标签 c string replace find

我正在尝试查找替换,但不仅针对字符串,还针对子字符串。因此,我正在开发的程序会查找单词“bar”并在“bar”的任何实例前面附加“foo”。所以我的方法是,我不是实际附加字符串,而是用“foobar”替换整个字符串“bar”。我现在拥有的代码(未完全测试)应该找到所有出现的“bar”并将其替换为“foobar”。但是,如果有一个看起来像“bar123abc”的字符串,它不会将其替换为“foobar123abc”。

这是我的代码:

static void replaceAllString(char *buf, const char *orig, const char *replace)
{
    int olen, rlen;
    char *s, *d;
    char *tmpbuf;

    if (!buf || !*buf || !orig || !*orig || !replace)
        return;

    tmpbuf = malloc(strlen(buf) + 1);
    if (tmpbuf == NULL)
        return;


    olen = strlen(orig);
    rlen = strlen(replace);

    s = buf;
    d = tmpbuf;

    while (*s) {
        if (strncmp(s, orig, olen) == 0) {
            strcpy(d, replace);
            s += olen;
            d += rlen;
        }
        else
            *d++ = *s++;
    }

    *d = '\0';

    strcpy(buf, tmpbuf);
    free(tmpbuf);
}

最佳答案

我可以这样做:

static char *replaceAll(char *buf, int buflen, const char *orig, const char *replace) {
    if (!buf || !*buf || !orig || !*orig || !replace) return buf;

    int olen = strlen(orig), rlen = strlen(replace);

    int max = strlen(buf) + 1;
    if (olen < rlen) {
        max = rlen * ((max / olen) + 1) + 1;
    }
    char *tmpbuf = malloc(max);
    char *bp = buf, *tp = tmpbuf, *sp;

    while (NULL != (sp = strstr(bp, orig))) {
        int f = sp - bp;
        memmove(tp, bp, f);
        memmove(tp + f, replace, rlen);
        tp += f + rlen;
        bp += f + olen;  // no recursive replacement
    }
    strcpy(tp, bp);
    strncpy(buf, tmpbuf, buflen);
    free(tmpbuf);
    return buf;
}

char haystack[128] = "123bar456bar7ba8ar9bar0";

int main(int ac, char *av[]) {
    printf("%s\n", replaceAll(haystack, sizeof haystack, "bar", "foobar"));
}

注意:传递 buflen 不是可选的!您不要写入您不知道长度的内存缓冲区。如果我正在面试 C 程序员,这将立即“不雇用”。 tmpbuf 分配的长度为 max,这是针对最坏情况(例如“barbarbar”)粗略计算的。这里的繁重工作是由 strstr() 完成的。

关于c - 查找替换子串C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735199/

相关文章:

c - C 中的 .dat 结构化文件处理(手动?)

C - 这行代码是什么意思?(关于结构)

无法让我的代码正常工作

c - 全局结构数组

vb.net - 如何在VB中反转列表?

Java 字符串基础

string - 截断 R 中字符串中的附加\n(换行符)

iphone - iOS Phonegap 正则表达式替换

c# - 使用 C# 搜索和替换文本文件中的值

用它们各自的总和替换分隔的数据帧值