[英]Find a replace a substring C
我正在尝试查找替换项,但不仅是字符串,而且还有子字符串。 因此,我正在开发的程序将查找单词“ bar”,并将“ foo”附加在“ bar”的任何实例之前。 所以我的方法是,不是实际附加字符串,而是将整个字符串“ bar”替换为“ foobar”。 我现在拥有的代码(未经完全测试)应该找到所有出现的“ 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()
完成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.