做你想做的事变得有点复杂,因为你需要处理以下场景:
- 替换比原版短 -- 因此您需要移动剩余的行以跟随替换文本以避免留下空白;
- replacement is same length as original -- 普通情况,用替换覆盖原来的;最后
- replacement is long than original -- 您必须验证原始字符串加上替换长度差异仍然适合原始字符串的存储,您必须将行尾复制到临时在进行替换之前先缓冲,然后将临时缓冲区中的其余行添加到末尾。
strtok 在这里有一些缺点,因为它在标记化过程中会更改原始字符串。 (您可以只制作一个副本,但如果您想要就地替换,则需要进一步查看)。 strstr 和 strcspn 的组合允许您在原始字符串中查找特定搜索字符串时以更有效的方式对原始字符串进行操作。
strcspn 可以像 strtok 一样使用一组分隔符来提供找到的当前令牌的长度(以确保 strstr 不匹配您的搜索词作为 lesser-included-substring 一个更长的单词,比如trees 中的tree)然后它变成了一个简单的问题,用strstr 循环并用strcspn 验证令牌的长度,然后只应用三种情况之一以上。
一个包含内嵌 cmets 以帮助您跟进的简短示例实现可能是:
#include <stdio.h>
#include <string.h>
#define MAXLIN 100
void wordreplace (char *str, const char *srch,
const char *repl, const char *delim)
{
char *p = str; /* pointer to str */
size_t lenword, /* length of word found */
lenstr = strlen (str), /* length of total string */
lensrch = strlen (srch), /* length of search word */
lenrepl = strlen (repl); /* length of replace word */
while ((p = strstr (p, srch))) { /* srch exist in rest of string? */
lenword = strcspn (p, delim); /* get length of word found */
if (lenword == lensrch) { /* word len match search len */
if (lenrepl == lensrch) /* if replace is same len */
memcpy (p, repl, lenrepl); /* just copy over */
else if (lenrepl > lensrch) { /* if replace is longer */
/* check that additional lenght will fit in str */
if (lenstr + lenrepl - lensrch > MAXLIN - 1) {
fputs ("error: replaced length would exeed size.\n",
stderr);
return;
}
if (!p[lenword]) { /* if no following char */
memcpy (p, repl, lenrepl); /* just copy replace */
p[lenrepl] = 0; /* and nul-terminate */
}
else { /* store rest of line in buffer, replace, add end */
char endbuf[MAXLIN]; /* temp buffer for end */
size_t lenend = strlen (p + lensrch); /* end length */
memcpy (endbuf, p + lensrch, lenend + 1); /* copy end */
memcpy (p, repl, lenrepl); /* make replacement */
memcpy (p + lenrepl, endbuf, lenend); /* add end after */
}
}
else { /* otherwise replace is shorter than search */
size_t lenend = strlen (p + lenword); /* get end length */
memcpy (p, repl, lenrepl); /* copy replace */
/* move end to after replace */
memmove (p + lenrepl, p + lenword, lenend + 1);
}
}
}
}
int main (int argc, char **argv) {
char str[MAXLIN] = "apple tree house in the elm tree";
const char *search = argc > 1 ? argv[1] : "tree",
*replace = argc > 2 ? argv[2] : "12",
*delim = " \t\n";
wordreplace (str, search, replace, delim);
printf ("str: %s\n", str);
}
使用/输出示例
您在"apple tree house in the elm tree" 中将"tree" 替换为"12" 示例:
$ ./bin/wordrepl_strstr_strcspn
str: apple 12 house in the elm 12
"tree" 与 "core" 的简单等长替换,例如
$ ./bin/wordrepl_strstr_strcspn tree core
str: apple core house in the elm core
"tree" 的“长于”替换为 "bobbing":
$ ./bin/wordrepl_strstr_strcspn tree bobbing
str: apple bobbing house in the elm bobbing
有很多不同的方法可以解决这个问题,所以没有一种方法是正确的。关键是使其易于理解和合理有效。如果您还有其他问题,请仔细查看并告诉我。