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
- C program to append content of one text file to another
- Find the word from a given sentence having given word as prefix
- Longest Common Prefix using Word by Word Matching
- Recursive program to replace all occurrences of pi with 3.14 in a given string
- Program to replace every space in a string with hyphen
- Java program to count the characters in each word in a given sentence
- Program to print the Alphabets of a Given Word using * pattern
- Check if a given string can be converted to another by given possible swaps
- Replace all occurrences of pi with 3.14 in a given string
- Replace every consonant sequence with its length in the given string
- Replace all occurrences of character X with character Y in given string
- Minimize cost to replace all the vowels of a given String by a single vowel
- URLify a given string (Replace spaces is %20)
- Justify the given Text based on the given width of each line
- Wrap every continuous instance of given word with some given string
- Program to copy the contents of one array into another in the reverse order
- Program to find Smallest and Largest Word in a String