Reimplement C++ string replace()

I'm not sure why I didn't use string_view.find() to begin with.
This commit is contained in:
Oliver Hamlet
2025-08-12 19:10:01 +01:00
parent d5ff75ee31
commit 27c57527d7
+10 -9
View File
@@ -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;
}