简体   繁体   English

查找替换子字符串C

[英]Find a replace a substring C

I am trying to do a find a replace but not just for strings but for substrings also. 我正在尝试查找替换项,但不仅是字符串,而且还有子字符串。 So the program I am working on looks for the word "bar" and append "foo" in front of any instance of "bar". 因此,我正在开发的程序将查找单词“ bar”,并将“ foo”附加在“ bar”的任何实例之前。 So my approach is that instead of actually appending the string, I replace the whole string "bar" with "foobar". 所以我的方法是,不是实际附加字符串,而是将整个字符串“ bar”替换为“ foobar”。 The code I have right now (not fully tested), should find and replace all occurrences of "bar" with "foobar". 我现在拥有的代码(未经完全测试)应该找到所有出现的“ bar”并替换为“ foobar”。 However, if there is a string that looks like "bar123abc", it does not replace it with "foobar123abc". 但是,如果有一个看起来像“ bar123abc”的字符串,则不会将其替换为“ foobar123abc”。

This is the code I have: 这是我的代码:

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);
}

Here's how I might do it: 这是我可能的方法:

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"));
}

Note: passing buflen is NOT optional! 注意:传递buflen不是可选的! You DO NOT write to memory buffers you don't know the length of. 您不要写入您不知道其长度的内存缓冲区。 If I'm interviewing C programmers, this would be an instant "no hire". 如果我正在采访C程序员,那将是立即的“不聘用”。 tmpbuf is allocated the length max , crudely calculated for the worst case (something like "barbarbar"). tmpbuf分配了max的长度,该长度是为最坏情况(例如“ barbarbar”)粗略计算得出的。 The heavy lifting here is done by strstr() . 这里繁重的工作是由strstr()完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM