OneBite.Dev - Coding blog in a bite size

replace multiple words in a string in C

Code snippet on how to replace multiple words in a string in C

  #include <stdio.h>
  #include <string.h>

  int main()
  {
      char str[100] = "This is an example sentence!";
      char *find = "is";
      char *replace = "was";
         
      char *p;
     
      while(p=strstr(str, find))
      {
          int len = strlen(find);
          strncpy(p, replace, len);
      }
      
      printf("%s\n", str);
     
      return 0;
  }

This code replaces every instance of the word “is” with the word “was” in the string “This is an example sentence!“. It does this by using the strstr() function, which looks for the first instance of a given word within a string. The next step is to copy the replacement word into the string by using the strncpy() function, where the number of characters to be copied is given by the length of the original word “is”. Lastly, the modified string is printed out with the printf() function.

c