OneBite.Dev - Coding blog in a bite size

replace a word in a string in C

Code snippet on how to replace a word in a string in C

  #include <stdio.h>
  #include <string.h>
  int main () {
    char str[80] = "The quick brown fox";
    char *p;
    /* Replace first occurrence of "brown" with "red" */
    if ((p=strstr(str,"brown")) != NULL) {
      strncpy(p,"red",3);
    }
    printf("%s\n", str);
    return 0;
  }

This code snippet will replace the first occurrence of the word “brown” from the given string with “red”. First, the code includes the header files <string.h> and <stdio.h> which provides functions for manipulating strings and printing data respectively. Next, a variable str is declared which is a string containing the phrase “The quick brown fox”. The function strstr() is used to search for the first occurrence of the word “brown” in the string. If the word is found, a pointer “p” is assigned to that location in the string. Then, the function strncpy() is used to replace the word “brown” with the word “red”. Finally, the updated string is printed out using the printf() function.

c