[ create a new paste ] login | about

Link: http://codepad.org/glHPVdoL    [ raw code | output | fork ]

C, pasted on Jun 7:
char *strrstr(char *str, char *substr, char *restr)
{
    int n, i, len, sublen, relen;
    char **pps; //array of pointers to occurrences of substr in str
    len = strlen(str);
    relen = strlen(restr);
    sublen = strlen(substr);
    if (sublen == 0)
        return(strdup(str));
    pps = (char **)malloc(sizeof(char *) * len / sublen);//max possible size
    char *pin, *pc = str;
    n = 0;
    while (*pc != 0){ //find the occurrences
        pin = strstr(pc, substr);
        if (pin != 0){
            pps[n++] = pin;
            pc = pin + sublen;

        }
        else
            break;
    }                    //now know how big to make output string
    int outlen = len + n * (relen - sublen);
    char *outstr = (char *)malloc(outlen + 1);
    outstr[outlen] = 0;
    char *pco = outstr;
    pc = str;               //go along input str
    for (i = 0; i < n; ++i){  //each occurrence of substr
        while (*pc != 0 && pc < pps[i])//copy str to outstr until occurrence
            *pco++ = *pc++;
        strcpy(pco, restr);    //copy replacement string
        pc += sublen;          //skip substring in input
        pco += relen;          //skip replacement in output
    }
    while (*pc != 0)           //copy str to outstr after last occurrence
        *pco++ = *pc++;

    free(pps);
    return(outstr);
}
int main(int argc, char **argv)
{
    int len = 100000;
    char *pa = "a";
    char *pb = "b";
    char * str = (char *)malloc(len + 1);
    memset(str, 'a', len);
    str[len] = 0;
    
    char *outstr = strrstr(str, pa, pb);                    
    
    str[41] = 0;
    puts(str);
    puts(str + len - 40);
    outstr[41] = 0;
    puts(outstr);
    puts(outstr + len - 40);

    free(str);
    free(outstr);
    return(0);
}


Output:
1
2
3
4
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb


Create a new paste based on this one


Comments: