src/OCString.c
// You must free the result if result is non-NULL.
You must free the result if result is non-NULL.
You must free the result if result is non - NULL .
char *str_replace(char *orig, char *rep, char *with, int64_t *count) {
    char *result; 
    char *ins;    
    char *tmp;    
    size_t len_rep;  
    size_t len_with; 
    long len_front; 
    if (!orig || !rep)
        return NULL;
    len_rep = strlen(rep);
    if (len_rep == 0)
        return NULL; 
    if (!with)
        with = "";
    len_with = strlen(with);
    ins = orig;
    for ((*count) = 0; (tmp = strstr(ins, rep)); ++(*count)) {
        ins = tmp + len_rep;
    }
    tmp = result = malloc(strlen(orig) + (len_with - len_rep) * (*count) + 1);
    if (!result)
        return NULL;
    while ((*count)--) {
        ins = strstr(orig, rep);
        len_front = ins - orig;
        tmp = strncpy(tmp, orig, len_front) + len_front;
        tmp = strcpy(tmp, with) + len_with;
        orig += len_front + len_rep; 
    }
    strcpy(tmp, orig);
    return result;
}
char * str_replace ( char * orig , char * rep , char * with , int64_t * count ) { char * result ; char * ins ; char * tmp ; size_t len_rep ; size_t len_with ; long len_front ; if ( ! orig || ! rep ) return NULL ; len_rep = strlen ( rep ) ; if ( len_rep == 0 ) return NULL ; if ( ! with ) with = " " ; len_with = strlen ( with ) ; ins = orig ; for ( ( * count ) = 0 ; ( tmp = strstr ( ins , rep ) ) ; ++ ( * count ) ) { ins = tmp + len_rep ; } tmp = result = malloc ( strlen ( orig ) + ( len_with - len_rep ) * ( * count ) + 1 ) ; if ( ! result ) return NULL ; while ( ( * count ) -- ) { ins = strstr ( orig , rep ) ; len_front = ins - orig ; tmp = strncpy ( tmp , orig , len_front ) + len_front ; tmp = strcpy ( tmp , with ) + len_with ; orig += len_front + len_rep ; } strcpy ( tmp , orig ) ; return result ; }
You must free the result if result is non-NULL.
You must free the result if result is non - NULL .
// the return string // the next insert point // varies // length of rep (the string to remove) // length of with (the string to replace rep with) // distance between rep and end of last rep // sanity checks and initialization // empty rep causes infinite loop during count // count the number of replacements needed // first time through the loop, all the variable are set correctly // from here on, //    tmp points to the end of the result string //    ins points to the next occurrence of rep in orig //    orig points to the remainder of orig after "end of rep" // move to next "end of rep"