An informative article about c++ programming , submitted by a fan of us "Allan Bogh" From USA.
Allan Bogh : 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.
CODE
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.
0 comments:
Post a Comment