Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

replace a substring with another substring in c

char* replace(const char* sSource, unsigned int nSearch, unsigned int nReplace){
    unsigned int subStrIndex = findocc(sSource, nSearch);

    int i =0;
    unsigned int j = nSearch;
    // find the size of the number to search and replace it as a string
    while(nSearch > 0){nSearch /=10 ; i++;}
    char * buff1 = calloc(i, sizeof(char));
    sprintf(buff1, "%d", j);


    i =0;
    j = nReplace;
    // find the size of the number to replace and replace is as a string
    while(nReplace > 0){nReplace /=10 ; i++;}
    char * buff2 = calloc(i, sizeof(char)) ;
    sprintf(buff2, "%d", j);

    // allocate memory and copy the part before the pattern we are searching for
    char * new = calloc(subStrIndex , sizeof(char));
    new = strncat(new, sSource, subStrIndex);

    // go to the index where the pattern we are searching for
    sSource +=subStrIndex;

    // assign pointer to the enter of the sSource
    const char * last = sSource + strlen((sSource));

    // go forward until the sSource is not equal to buff by the value;
    while(*sSource == *buff1) {++sSource;++buff1;}

    // find the last chars that we need to copy
    unsigned int rest = last - sSource;

    // copy what we need to replace
    new = strcat(new, buff2);

    // copy the last part
    new = strncat(new, sSource, rest);

    return new;


}
 
PREVIOUS NEXT
Tagged: #replace #substring #substring
ADD COMMENT
Topic
Name
1+4 =