C++: Replace text without searching the replacement again
A replacement may contain the text being searched for. Advancing past the inserted text prevents the loop from repeatedly replacing its own output.
Prepare a scratch directory
Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save as cpp-string-replace-skip-inserted-text.cpp:
#include <cassert>
#include <iostream>
#include <stdexcept>
#include <string>
std::string replace_all(std::string text, const std::string& needle,
const std::string& replacement) {
if (needle.empty()) throw std::invalid_argument("empty needle");
std::size_t position = 0;
while ((position = text.find(needle, position)) != std::string::npos) {
text.replace(position, needle.size(), replacement);
position += replacement.size();
}
return text;
}
int main() {
std::cout << replace_all("a-b-a", "a", "aa") << '\n';
std::cout << replace_all("banana", "na", "") << '\n';
assert(replace_all("aaa", "aa", "x") == "xa");
assert(replace_all("plain", "z", "q") == "plain");
assert(replace_all("", "a", "b").empty());
bool rejected = false;
try { (void)replace_all("a", "", "b"); }
catch (const std::invalid_argument&) { rejected = true; }
assert(rejected);
}Compile and run:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-string-replace-skip-inserted-text.cpp -o cpp-string-replace-skip-inserted-text &&
./cpp-string-replace-skip-inserted-textObserved output:
aa-b-aa
baHow it works
The next search starts immediately after the replacement. An empty replacement leaves the index in place, where the following original characters have shifted. The empty-needle guard makes the progress rule explicit. Matches are consumed left to right without overlap, as the assertion for aaa demonstrates.
Limits and choices
The function receives its working text by value and returns a new string. It performs literal byte-sequence matching with std::string; it has no Unicode normalization or case folding. Repeated shifts can make large replacements expensive, and allocation can fail. Set size limits when processing untrusted input.
The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.
Clean up
rm -- cpp-string-replace-skip-inserted-text.cpp cpp-string-replace-skip-inserted-text
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect the remaining files before removing anything else.
Acknowledgements
This post was created with assistance from AI.