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 xx for xx New String: GeeksforGeeks Geeks for Geeks
Method 2: This method involves inplace update of string. It is more efficient as it uses only extra space for the new characters to be inserted.
1 xxforxx xx for xx xx geeks
geeksforgeeks geeks for geeks
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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- C program to find and replace a word in a File by another given word
- Lex code to replace a word with another word in a file
- Program to replace a word with asterisks in a sentence
- Longest Common Prefix using Word by Word Matching
- Program to find the Encrypted word
- Lex program to search a word in a file
- Program to print the Alphabets of a Given Word using * pattern
- Program for length of the longest word in a sentence
- Lex program to find the length of the longest word
- 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
- Second most repeated word in a sequence
- Encoding a word into Pig Latin
- Minimum Word Break
- Length Of Last Word in a String
- First substring whose reverse is a word in the string