OneBite.Dev - Coding blog in a bite size

replace a substring within a string in C

Code snippet on how to replace a substring within a string in C

  char *myReplace(char *origString, char *oldSubString, char *newSubString) {
    char buffer[BUFFER_SIZE];
    char *ch;
  
    //Check if the strings are same
    if(!(ch = strstr(origString, oldSubString)))
      return origString;
  
    //Copy characters from the original string before the substring
    strncpy(buffer, origString, ch - origString + 1);
    
    //Concatenate newSubString and characters following the original substring
    sprintf(buffer + (ch - origString), "%s%s", newSubString,
            ch + strlen(oldSubString));
  
    return strdup(buffer);
  }

This code replaces a substring within another string, by taking in three parameters: the original string, the substring to be replaced and the new substring. First, it checks if the old and new substrings are the same, and returns the original string if so. If not, it copies characters from the original string up to the start of the old substring. Then, it concatenates the new substring and the characters following the original substring. Lastly, it creates an identical duplicate of the resulting string and returns it.

c