I’ve been privileged by higher-level language string functions, such as PHP’s easy to use str_replace function, that I’ve forgotten how performing such simple tasks in lower-level languages like C++ can be such a hassle. Aside from using some library (of which I’m not aware yet), here’s a simple string replace function which is similar to the PHP version. In this case the function will directly modify the original string, not return an instance of a new string.
void str_replace(std::string& str, const std::string find, const std::string replace){ size_t index = 0; while (true) { /* Locate the substring to replace. */ index = str.find(find, index); if (index == std::string::npos) break; /* Make the replacement. */ str.replace(index, find.length(), replace); /* Advance index forward one spot so the next iteration doesn't pick it up as well. */ ++index; } }
Usage:
std::string str = "Hello Earth!"; str_replace(str,"Earth","World"); //str is "Hello World!" now.