![]() |
VOOZH | about |
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:
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:
1 xxforxx xx for xx xx geeks
geeksforgeeks geeks for geeks
Time Complexity: O(n)
Auxiliary Space: O(1)