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 firstname.lastname@example.org. 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.
- Program to replace a word with asterisks in a sentence
- Longest Common Prefix using Word by Word Matching
- Program for length of the longest word in a sentence
- Java program to count the characters in each word in a given sentence
- Program to find Smallest and Largest Word in a String
- Fibonacci Word
- Tribonacci Word
- Possibility of a word from a given set of characters
- Next word that does not contain a palindrome and has characters from first k
- Minimum Word Break
- Length Of Last Word in a String
- Second most repeated word in a sequence
- Encoding a word into Pig Latin
- Print last character of each word in a string
- Print the first and last character of each word in a String
Improved By : Didi17