VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-replace-word-text-another-given-word/

⇱ C Program to Replace a Word in a Text By Another Given Word - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 11 Mar, 2023

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

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:

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:

Input:
1
xxforxx xx for xx
xx
geeks
Output:
geeksforgeeks geeks for geeks

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

Comment
Article Tags: