OneBite.Dev - Coding blog in a bite size

remove a substring from a string in C

Code snippet on how to remove a substring from a string in C

  #include <stdio.h>
  #include <string.h>
  
  int main()
  {
      char str[100] = "The quick brown fox jumps over the lazy dog";
      char sub[10] = "the";
      char *ptr;
  
      /* Removes the string pointed to by sub from str */
      ptr = strstr(str, sub);
      memmove(ptr, ptr+strlen(sub), 1+strlen(ptr+strlen(sub)));
  
      printf("%s", str);
  
      return 0;
  }

This code removes a substring ‘the’ from a given string ‘The quick brown fox jumps over the lazy dog’. It begins by including the library files stdio.h and string.h in the program which contains the functions printf(), strstr() and memmove(). Then it declares a string str and a substring sub and a pointer(ptr) which will be used later in the program. The string str is initialized with a string value which contains the substring to be removed. The strstr() function is used to search the substring in the string and the pointer is assigned the address of the first occurrence of “the” in the string. The memmove() function is used to move the characters after the substring to the address pointed by the pointer. The variable str is then printed which now does not contain the substring “the”. Finally 0 is returned from the program.

c