Programming Tips - C++: Change all occurrences of one character to another

Date: 2020may22 Language: C++ Q. C++: Change all occurrences of one character to another A. Since there is no length change, old school is best:
void changeAllChar(std::string &s, const char before, const char after) { for (int i = 0; i < s.size(); i++) { if (s[i] == before) s[i] = after; } }
You can also use std::replace() from <algorithm>:
#include <algorithm> void changeAllChar(std::string &s, const char before, const char after) { std::replace(s.begin(), s.end(), before, after); }
Neither of these work for replacing a string.