2014-11-08 117 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"; 

在一個串置換序列時然而要小心,這樣就不會具有更長替換較短的子串,然後作爲你可能會寫在字符串的末尾。