Saturday, February 14, 2009

Console: Search and replace with std::string (C++)

Let's face it. std::string is a thousand times better than a char*. It is widely used to store input and output. Not to mention convenient. However, it lacks some important features. Searching and replacing portions of the text would be a very neat feature indeed. A feature like that isn't already made for us, so we have to make our own. It's a good thing std::string has find() and insert().

Here's the function and an example of how to use it. It replaces "Joe" with "Mike".
#include <iostream>

std::string Replace(std::string Str, std::string Old, std::string New)
// the location of the string to replace string
int x;

// while we can find the str to replace
while( (x=Str.find(Old)) >= 0 )
// for every character in the string to replace
for (std::string::size_type i = 0; i < Old.length(); i++)
// replace it with ""
Str.replace(x, 1, "");

// then insert our new string into the main one
Str.insert(x, New);

// after we're done, return the new, replaced string
return Str;

int main()
// make an example string, then replace
std::string exampleStr = "Hi! Are you Joe?";
exampleStr = Replace(exampleStr, "Joe", "Mike");

// print string
std::cout << exampleStr.c_str();

return 0;


Post a Comment


C++ Universe - The universe compromised of C++ and C#. Powered By Blogger © 2009.