Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
C program to find and replace a word in a File by another given word
Next article icon

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

Last Updated : 11 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given three strings ‘str’, ‘oldW’ and ‘newW’. The task is find all occurrences of the word ‘oldW’ and replace then with word ‘newW’. Examples:

Input : str[] = "xxforxx xx for xx",          oldW[] = "xx",          newW[] = "geeks" Output : geeksforgeeks geeks for geeks
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

The idea is to traverse the original string and count the number of times old word occurs in the string. Now make a new string of sufficient size so that new word can be replaced. Now copy original string to new string with replacement of word. 

Implementation:

C




// C program to search and replace
// all occurrences of a word with
// other word.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// Function to replace a string with another
// string
char* replaceWord(const char* s, const char* oldW,
                const char* newW)
{
    char* result;
    int i, cnt = 0;
    int newWlen = strlen(newW);
    int oldWlen = strlen(oldW);
 
    // Counting the number of times old word
    // occur in the string
    for (i = 0; s[i] != '\0'; i++) {
        if (strstr(&s[i], oldW) == &s[i]) {
            cnt++;
 
            // Jumping to index after the old word.
            i += oldWlen - 1;
        }
    }
 
    // Making new string of enough length
    result = (char*)malloc(i + cnt * (newWlen - oldWlen) + 1);
 
    i = 0;
    while (*s) {
        // compare the substring with the result
        if (strstr(s, oldW) == s) {
            strcpy(&result[i], newW);
            i += newWlen;
            s += oldWlen;
        }
        else
            result[i++] = *s++;
    }
 
    result[i] = '\0';
    return result;
}
 
// Driver Program
int main()
{
    char str[] = "xxforxx xx for xx";
    char c[] = "xx";
    char d[] = "Geeks";
 
    char* result = NULL;
 
    // oldW string
    printf("Old string: %s\n", str);
 
    result = replaceWord(str, c, d);
    printf("New String: %s\n", result);
 
    free(result);
    return 0;
}
 
 
Output:
Old string: xxforxx xx for xx New String: GeeksforGeeks Geeks for Geeks

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 2: This method involves the in-place update of the string. It is more efficient as it uses only extra space for the new characters to be inserted. 

Implementation:

C




// C Program to replace a word in a text by another given
// word by inplace updation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void replaceWord(char* str, char* oldWord, char* newWord)
{
    char *pos, temp[1000];
    int index = 0;
    int owlen;
 
    owlen = strlen(oldWord);
 
    // Repeat This loop until all occurrences are replaced.
 
    while ((pos = strstr(str, oldWord)) != NULL) {
        // Bakup current line
        strcpy(temp, str);
 
        // Index of current found word
        index = pos - str;
 
        // Terminate str after word found index
        str[index] = '\0';
 
        // Concatenate str with new word
        strcat(str, newWord);
 
        // Concatenate str with remaining words after
        // oldword found index.
        strcat(str, temp + index + owlen);
    }
}
 
int main()
{
    char str[1000], oldWord[100], newWord[100];
    printf("Enter the string: ");
    gets(str);
 
    printf("Enter the word to be replaced: ");
    gets(oldWord);
 
    printf("Replace with: ");
    gets(newWord);
 
    replaceWord(str, oldWord, newWord);
 
    printf("\nModified string: %s", str);
 
    return 0;
}
 
 
Input:
1 xxforxx xx for xx xx geeks
Output:
geeksforgeeks geeks for geeks

Time Complexity: O(n)
Auxiliary Space: O(1)



Next Article
C program to find and replace a word in a File by another given word
author
kartik
Improve
Article Tags :
  • C Language
  • C Programs
  • DSA
  • Strings
  • C Strings Programs
Practice Tags :
  • Strings

Similar Reads

  • C program to find and replace a word in a File by another given word
    Pre-requisite: File Handling in CGiven a file containing some text, and two strings wordToBeFind and wordToBeReplacedWith, the task is to find all occurrences of the given word 'wordToBeFind' in the file and replace them with the given word ‘wordToBeReplacedWith’. Examples: Input : File = "xxforxx x
    3 min read
  • Lex code to replace a word with another word in a file
    Given a text file as input, the task is to replace a given word with another word in the file. Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the
    2 min read
  • C Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples:  Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "
    3 min read
  • C# Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "p
    4 min read
  • Lex program to search a word in a file
    Problem: Write a Lex program to search a word in a file. Explanation: FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs
    2 min read
  • C Program to Print the First Letter of Each Word
    In a string that contains multiple words, each word is separated by a whitespace. In this article, we will learn how to print the first letter of each word using a C program. The simplest method to print the first letter of each word is by using a loop. Let’s take a look at an example: [GFGTABS] C #
    3 min read
  • How to store words in an array in C?
    We all know how to store a word or String, how to store characters in an array, etc. This article will help you understand how to store words in an array in C. To store the words, a 2-D char array is required. In this 2-D array, each row will contain a word each. Hence the rows will denote the index
    2 min read
  • C Program For Lower Case to Uppercase and Vice-Versa in a File
    Given a text file(gfg.txt), our task is to convert all the lowercase characters of the file into uppercase. ExamplesInput: (content inside file gfg.txt) An extensive classroom programme by GeeksforGeeks to build and enhance Data Structures and Algorithm concepts Output: (content inside file gfg.txt)
    4 min read
  • C Program to Swap Adjacent Characters of a String
    In this article, we will learn how to swap adjacent characters of a string in C. To swap all adjacent characters in a string, the string must have an even number of characters. If the number of characters is odd, the last character remains unswapped since it has no adjacent element. The most straigh
    3 min read
  • How to Split a String by a Delimiter in C?
    Splitting a string by a delimiter is a common task in programming. In C, strings are arrays of characters, and there are several ways to split them based on a delimiter. In this article, we will explore different methods to split a string by a delimiter in C. Splitting Strings in CThe strtok() metho
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences