![]() |
VOOZH | about |
Given a string and a target substring, the task is to replace all occurrences of the target substring with a new substring. For Example:
Input: "python java python html python"
Replace "python" --> "c++"
Output: "c++ java c++ html c++"
Below are multiple methods to replace all occurrences efficiently.
The replace() method directly replaces all occurrences of a substring with the new string.
c++ java c++ html c++
Explanation: a.replace(old, new) replaces every instance of old with new.
This method uses re.sub() to replace all matches of a pattern with the new substring. It is useful for complex patterns or multiple variations.
c++ java c++ html c++
Explanation: re.sub(pattern, replacement, string) finds all occurrences of pattern and replaces them with replacement.
This method splits the string at each occurrence of the target and joins it back with the replacement. It works well but is less efficient for very long strings.
c++ java c++ html c++
Explanation:
This method builds a new string by checking each slice for the target substring. It is least efficient but works without built-in functions.
c++ java c++ html c++
Explanation: