Replace All Occurrences

Easy~10 min

Given a string s, a target substring, and a replacement string, replace all occurrences of target in s with replacement.

Do not use any built-in replace or replaceAll methods. Implement the replacement logic manually.

Return the resulting string after all replacements are made.

Examples

Example 1
Input: s = "hello world hello", target = "hello", replacement = "hi"
Output: "hi world hi"
Explanation: Both occurrences of "hello" are replaced with "hi".
Example 2
Input: s = "aaa", target = "a", replacement = "bb"
Output: "bbbbbb"
Explanation: Each "a" is replaced with "bb", resulting in "bbbbbb".
Example 3
Input: s = "abc", target = "d", replacement = "e"
Output: "abc"
Explanation: The target "d" is not found in "abc", so the string is unchanged.

Constraints

  • 0 <= s.length <= 10^4
  • 1 <= target.length <= 100
  • 0 <= replacement.length <= 100
  • s, target, and replacement consist of printable ASCII characters
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run