Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Replace a Word in a Text By Another Given Word


Write a C program to replace a specific word in a text with another word provided by the user.

  • Initializes a source string and two words — one to find ("apple") and one to replace with ("orange").
  • Scans through the source string character-by-character to check if the current position matches "apple".
  • If a match is found, it copies "orange" into the result string and skips over "apple" in the original.
  • If no match is found, it copies the current character as-is, and finally prints the modified string.
Example : pgm.c
#include <stdio.h>

int main() {
    char str[] = "I love apple";
    char result[100];
    char wordToReplace[] = "apple";
    char replaceWith[] = "orange";

    int i = 0, j = 0, k, match;

    while (str[i] != '\0') {
        match = 1;
        // Check for the word "apple" in current position
        for (k = 0; wordToReplace[k] != '\0'; k++) {
            if (str[i + k] != wordToReplace[k]) {
                match = 0;
                break;
            }
        }

        if (match) {
            // Copy "orange" into result
            for (k = 0; replaceWith[k] != '\0'; k++) {
                result[j++] = replaceWith[k];
            }
            i += 5; // Skip "apple" (length = 5)
        } else {
            // Copy character as is
            result[j++] = str[i++];
        }
    }

    result[j] = '\0';

    printf("Original String: %s\n", str);
    printf("Modified String: %s\n", result);

    return 0;
}

Output :

Original String: I love apple
Modified String: I love orange