2014-11-08 234 views
0

如何在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; 
} 

回答

2

简短的答案是使用现有的字符串替换函数。我的网站上有一个在http://creativeandcritical.net/str-replace-c/(当前版本名为replace_str2)。您需要对代码进行的更改(测试)为:

  • #include <stddef.h>添加到其他包括。
  • replace_str2函数复制到replacehtmlentities函数之上的文件中。
  • 改变功能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; 
    
  • 在主,你该函数的调用更改为:

    str = replacehtmlentities(str); 
    

作为补充说明:在main中,str将n用malloc分配的引用内存。如果/当你不再需要这个字符串时,你可以通过调用free(str)来释放内存。

+0

我明白了。非常感谢你! :-) – 2014-11-09 14:16:09

+0

不客气!很高兴它的工作。 – Laird 2014-11-09 14:33:50

2

指针str指向一个字符串,字符串字面量是只读(即不变)。尝试修改字符串文字将导致undefined behavior

的解决方案是很简单的:声明str作为数组:

char str[] = "space &nbsp; lowerthan &lt; end"; 

在一个串置换序列时然而要小心,这样就不会具有更长替换较短的子串,然后作为你可能会写在字符串的末尾。