c - 在字符串中搜索和替换

标签 c string replace html-entities

我如何在 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[] = {
        { "&nbsp;", " " },
        { "&lt;", "<" },
        { "&gt;", ">" },
        { "&amp;", "&" },
        { "&euro;", "€" },
        { "&copy;", "©" },
        { "&reg;", "®" },
        { 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 &nbsp; lowerthan &lt; 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/

相关文章:

python - C:初始化二叉堆

c - 通过 USB 获取系统日期/时间

java - ArrayList 或单个 String 之间的操作性能

java - 关于使用 Scanner 类创建类、设置方法和 String 数据类型的问题

javascript - 在 jQuery 中替换小数

c - C中的递归深度是否有任何硬连线限制

c - 是否在函数内部使用 calloc,更改作为函数参数传递的指针

python - 从特定字符后的字符串中提取数字

regex - 在 Notepad++ 中使用查找和替换时引用正则表达式

java - 在java中替换字符串中的数字