In this program, we have given three strings txt, oldword, newword. Our task is to create a C program to replace a word in a text by another given word.
The program will search for all the occurrences of the oldword in the text and replace it with newword.
Let’s take an example to understand the problem −
Input
text = “I am learning programming” oldword = “learning” newword = “practicing”
Output
“I am practicing programming”
To solve this problem, we will first find the number of occurrence of the oldword in the string and then create a new string which will store the text with replaced words.
C program to Replace a word in a text by another given word
// C program to Replace a word in a text by another given word
Example
#include <stdio.h> #include <string.h> #include <stdlib.h> void replaceWordInText(const char *text, const char *oldWord, const char *newWord) { int i = 0, cnt = 0; int len1 = strlen(newWord); int len2 = strlen(oldWord); for (i = 0; text[i] != '\0'; i++) { if (strstr(&text[i], oldWord) == &text[i]) { cnt++; i += len2 - 1; } } char *newString = (char *)malloc(i + cnt * (len1 - len2) + 1); i = 0; while (*text) { if (strstr(text, oldWord) == text) { strcpy(&newString[i], newWord); i += len1; text += len2; } else newString[i++] = *text++; } printf("New String: %s\n", newString); } int main() { char str[] = "I am learning programming"; char c[] = "learning"; char d[] = "practicing"; char *result = NULL; printf("Original string: %s\n", str); replaceWordInText(str, c, d); return 0; }
Output
Original string: I am learning programming New String: I am practicing programming