If you want to do it quickly, you can use a two scan approach. Pseudo code:
- First parse. Find how many matching characters.
- Expand the length of the string.
- Second parse. Start from the end of the string. When we get a match we replace, else we just copy the chars from the first string.
I am not sure if this can be optimized to an in-place algorithm.