Fundamentals/String Immutability
← PrevNext →
Implement safeModifyString(s, index, newChar) that returns a new string formed by replacing the character at position index in s with newChar. Strings are treated as immutable, so you must build and return a fresh string rather than mutating the original.
If index is out of bounds (negative or greater than or equal to the length of s), return the original string s unchanged. Otherwise, the result has the same length as s with only the character at position index swapped for newChar.
Input
s: the original string
index: the position to modify (0-based)
newChar: the replacement character (passed as a value to splice in)
Output
A new string with the character at index replaced, or s itself when index is out of range.
Examples
Example 1
Inputs = "hello", index = 0, newChar = 3
Output"3ello"
Explanation: The character at position 0 is replaced with 3, producing a new string.
Example 2
Inputs = "abcde", index = 1, newChar = 1
Output"a1cde"
Example 3
Inputs = "a", index = 2, newChar = 2
Output"a"
Explanation: index 2 is out of bounds for a length-1 string, so the original is returned.
Constraints
Do not mutate s in place.
Return s unchanged when index < 0 or index >= length of s.