If you want to do it quickly, you can use a two scan approach. Pseudo code:
- Firstfirst parse. Findfind how many matching characterschars.
- Expandexpand the length of the string.
- Secondsecond parse. Start from the end of the string. When 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 algorithmalgo.
And a C++11 code example but I only search for one char.
#include <string> #include <iostream> #include <algorithm> using namespace std; void ReplaceString(string& subject, char search, const string& replace) { size_t initSize = subject.size(); int count = 0; for (auto c : subject) { if (c == search) ++count; } size_t idx = subject.size()-1 + count * replace.size()-1; subject.resize(idx + 1, '\0'); string reverseReplace{ replace }; reverse(reverseReplace.begin(), reverseReplace.end()); char *end_ptr = &subject[initSize - 1]; while (end_ptr >= &subject[0]) { if (*end_ptr == search) { for (auto c : reverseReplace) { subject[idx - 1] = c; --idx; } } else { subject[idx - 1] = *end_ptr; --idx; } --end_ptr; } } int main() { string s{ "Mr John Smith" }; ReplaceString(s, ' ', "%20"); cout << s << "\n"; }