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.
char *str_replace ( const char *string, const char *substr, const char *replacement ){
char *tok = NULL;
char *newstr = NULL;
char *oldstr = NULL;
if ( substr == NULL || replacement == NULL ) return strdup (string);
newstr = strdup (string);
while ( (tok = strstr ( newstr, substr ))){
oldstr = newstr;
newstr = malloc ( strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1 );
memset(newstr,0,strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1);
if ( newstr == NULL ){
free (oldstr);
return NULL;
}
memcpy ( newstr, oldstr, tok - oldstr );
memcpy ( newstr + (tok - oldstr), replacement, strlen ( replacement ) );
memcpy ( newstr + (tok - oldstr) + strlen( replacement ), tok + strlen ( substr ), strlen ( oldstr ) - strlen ( substr ) - ( tok - oldstr ) );
memset ( newstr + strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) , 0, 1 );
free (oldstr);
}
return newstr;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…