Given three strings ‘str’, ‘oldW’ and ‘newW’. The task is find all occurrences of the word ‘oldW’ and replace then with word ‘newW’.
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.
Old string: xxforxx New String: GeeksforGeeks
Method 2(Inplace update of string, uses extra space only for the new characters to be inserted)
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- A Program to check if strings are rotations of each other or not
- Write a program to print all permutations of a given string
- Write a program to reverse an array or string
- Print list items containing all characters of a given word
- Program to validate an IP address
- Recursively print all sentences that can be formed from list of word lists
- Longest Common Prefix using Word by Word Matching
- In-place replace multiple occurrences of a pattern
- Word Break Problem using Backtracking
- Program to toggle all characters in a string
- Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of given word
- Find largest word in dictionary by deleting some characters of given string
- Replace all occurrences of string AB with C without using extra space
- Program to find second most frequent character
- C Program to Sort an array of names or strings
Improved By : Didi17