From 27c57527d77197a95ffc706edb8f3e243f172ee5 Mon Sep 17 00:00:00 2001 From: Oliver Hamlet Date: Tue, 12 Aug 2025 18:44:00 +0100 Subject: [PATCH] Reimplement C++ string replace() I'm not sure why I didn't use string_view.find() to begin with. --- cpp/src/api/exception/exception.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/cpp/src/api/exception/exception.cpp b/cpp/src/api/exception/exception.cpp index 9890e051..4146e9b8 100644 --- a/cpp/src/api/exception/exception.cpp +++ b/cpp/src/api/exception/exception.cpp @@ -33,17 +33,18 @@ std::string replace(std::string_view str, std::string out; out.reserve(str.size()); - size_t i = 0; - while (i < str.size()) { - if (i + from.size() <= str.size() && str.substr(i, from.size()) == from) { - out.append(to); - i += from.size(); - } else { - out.push_back(str[i]); - i += 1; - } + size_t startPos = 0; + auto findPos = str.find(from, startPos); + while (findPos != std::string_view::npos) { + out.append(str.substr(startPos, findPos - startPos)); + out.append(to); + + startPos = findPos + from.size(); + findPos = str.find(from, startPos); } + out.append(str.substr(startPos)); + return out; }