Last Updated: June 7, 2026
Produce a new string identical to s, except every space is swapped for ch. Every other character keeps its original value and position.
If the input has no spaces, the output equals the input. If the input is empty, the output is empty too.
The transformation is a one-to-one mapping. Positions never shift, because you swap one character for another rather than inserting or deleting anything. Only the spaces change, so the result has the same length as the input.
0 <= s.length <= 1000 → The string can be empty, in which case the result is also empty. The code must handle that without indexing into anything.Spaces can sit anywhere, so inspect each character. If the current character is a space, append ch. Otherwise, append the original character unchanged. The decision is local, so it never depends on what came before or after.
Build the result into a growable buffer rather than repeatedly concatenating onto a string, since some languages copy the entire string on every concatenation. By the end, the buffer holds the fully transformed string.
ch to the buffer.Take s = "a b c" with ch = '_'. Index 0 is a, not a space, so it is copied and the result is "a". Index 1 is a space, so _ is appended, giving "a_". Index 2 is b, copied to give "a_b". Index 3 is a space, so _ is appended, giving "a_b_". Index 4 is c, copied to give "a_b_c". The pass is complete.
Each step only looks at the single character under the current index, with no need to look ahead or backtrack. The buffer grows by exactly one character per step, so after processing all five input characters it holds five output characters.