Search
 
SCRIPT & CODE EXAMPLE
 

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;


}
Comment

PREVIOUS NEXT
Code Example
C :: c median of array 
C :: class in oops 
C :: create node in c 
C :: stdio.h 
C :: macos prevent disk mounting 
C :: char ASCII in c 
C :: to execute a program using C 
C :: . Simulate MVT and MFT. 
C :: esp8266 wifi.config does not work 
C :: c program to find minimum of 5 numbers using conditional operator in c 
C :: how to print % in c 
C :: Create the static library libmy.a containing all the functions listed below: 
C :: print 0 1 2 3 4 in c while loop 
C :: What should main() return in C? 
C :: how to print logs when doing unit-testing in rust 
C :: boolean operators in c++ 
C :: *= operator 
C :: fungetc 
C :: obstacle avoiding robot in c++ program 
C :: String to Integer (atoi) 
C :: ansi c write unsigned short to file 
C :: convert calendar time to epoch in c programming 
C :: call cuda kernel from c parameters 
C :: How to scale all columns in dataframe in R? 
C :: convert char to int ascii in c function 
C :: how to compress a file in c 
C :: Integer Input/Output 
C :: c how to include variables of other c file 
C :: putting character in the begginig and end of sring C 
C :: c text modifiers 
ADD CONTENT
Topic
Content
Source link
Name
9+9 =