diff --git a/ch09/ex9_43.cpp b/ch09/ex9_43.cpp index 3d5ede7e..7ea91c88 100644 --- a/ch09/ex9_43.cpp +++ b/ch09/ex9_43.cpp @@ -18,18 +18,17 @@ using std::string; void Replace(string& s, const string& oldVal, const string& newVal) { - for (auto beg = s.begin(); beg != s.end(); ++beg) { - if (*beg != oldVal.front()) continue; - if (std::distance(beg, s.end()) < - std::distance(oldVal.begin(), oldVal.end())) - break; - if (string{beg, beg + oldVal.size()} == oldVal) { - auto pos = std::distance(s.begin(), beg); - s.erase(beg, beg + oldVal.size()); - s.insert(beg, newVal.cbegin(), newVal.cend()); - beg = std::next(s.begin(), pos + newVal.size() - 1); - } - } + for (auto beg = s.begin(); beg != s.end(); ) { + ++beg; + if (*beg != oldVal.front()) continue; + if (std::distance(beg, s.end()) < + std::distance(oldVal.begin(), oldVal.end())) + break; + if (string{ beg, beg + oldVal.size() } == oldVal) { + beg = s.erase(beg, beg + oldVal.size()); + beg = s.insert(beg, newVal.cbegin(), newVal.cend()) + newVal.size(); + } + } } int main()