我如何在 C 中进行搜索和替换?我正在尝试执行函数来替换字符串中的 html 实体。我已经有了查找 html 实体开头和结尾的功能,但我不知道如何替换它们。
这是我已经拥有的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct entity {
char *entity;
char *substitute;
};
void replacehtmlentities(char *str, char *dest) {
int i;
char *begin = NULL;
char *end;
struct entity entities[] = {
{ " ", " " },
{ "<", "<" },
{ ">", ">" },
{ "&", "&" },
{ "€", "€" },
{ "©", "©" },
{ "®", "®" },
{ NULL, NULL },
};
for (i = 0; entities[i].entity; i++) {
while (begin = strstr(str, entities[i].entity)) {
end = begin + strlen(entities[i].entity);
// how to replace
}
}
}
int main(int argc, char **argv) {
char *str = "space lowerthan < end";
printf("%s\n", str);
replacehtmlentities(str);
printf("%s\n", str);
return EXIT_SUCCESS;
}
最佳答案
简短的回答是使用现有的字符串替换函数。我的网站上有一个 http://creativeandcritical.net/str-replace-c/ (当前版本名为 replace_str2
)。您需要对代码进行更改才能使用它(经过测试):
- 添加
#include <stddef.h>
其他包括。 - 复制
replace_str2
函数到replacehtmlentities
上面的文件中功能。 改变函数的原型(prototype)
replacehtmlentities
到:char *replacehtmlentities(char *str)
向该函数添加以下变量声明:
char *tmp = NULL; char *tmp2 = str;
替换该函数中的代码:
while (begin = strstr(str, entities[i].entity)) { end = begin + strlen(entities[i].entity); // how to replace }
与:
tmp = replace_str2(tmp2, entities[i].entity, entities[i].substitute);
if (i) free(tmp2);
tmp2 = tmp;
向该函数添加最终返回:
return tmp2;
在 main 中,将该函数的调用更改为:
str = replacehtmlentities(str);
作为附加说明:在 main 中,str 现在将引用使用 malloc 分配的内存。如果/当您不再需要此字符串时,您可以通过调用 free(str) 释放内存。
关于c - 在字符串中搜索和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26817017/