how to replace substring in c?

前端 未结 4 1675
[愿得一人]
[愿得一人] 2020-12-06 21:20

This example works but I think that the memory leaks. Function used in the simple web server module and thus shared memory grows if you use this function.

          


        
4条回答
  •  执念已碎
    2020-12-06 22:03

    This will replace all occurrence of "str" with "rep" in "src"...

    void strreplace(char *src, char *str, char *rep)
    {
        char *p = strstr(src, str);
        do  
        {   
            if(p)
            {
                char buf[1024];
                memset(buf,'\0',strlen(buf));
    
                if(src == p)
                {
                    strcpy(buf,rep);
                    strcat(buf,p+strlen(str));  
                }
                else
                {
                    strncpy(buf,src,strlen(src) - strlen(p));
                    strcat(buf,rep);
                    strcat(buf,p+strlen(str));
                }
    
                memset(src,'\0',strlen(src));
                strcpy(src,buf);
            }   
    
        }while(p && (p = strstr(src, str)));
    }
    

提交回复
热议问题