将字符串内的特定的字符或字符串替换成另一个字符或字符串(纯C)

xiaoxiao2021-02-28  81

C代码和网页交互的时候,有些字符串的显示会有问题

比如在网页文本框里显示&、< >等

发给网页的字符串就要转换成   &    > 各种转换码可参考http://liuxufei.com/weblog/jishu/71.html

这就需要代码里把原有的字符串check,进行各种替换

往上有相关代码,不过都有各种问题,只能自己写

这份基本试用,可借鉴

//把source字符串里所有s1字符全部替换成字符s2

void replace_string(char *result, char *source, char* s1, char *s2) {     int i = 0;     int j = 0;     char *q=NULL;     char *p=NULL;     char *s = NULL;         p=source;          while(1)     {         s=source;         for(j=0;j<=i;j++)         {             q=strstr(s, s1);             if (NULL==q) return 0;             if (j == i)             {                 break;             }             s=q+strlen(s1);         }         strncpy(result, p, q-p);         result[q-p]= '\0';//very important, must attention!         strcat(result, s2);         strcat(result, q+strlen(s1));         strcpy(p,result);         i++;     }     strcpy(result, p);     }
转载请注明原文地址: https://www.6miu.com/read-76021.html

最新回复(0)