Wednesday, 25 August 2010

An example of replacing part of strings

Taking a bit of break from the Design Patterns this week. We look at a simple example of replacing part of the strings. For example you may have a program which prints out some customised letter. You may want to replace the default name with the name of a person that can be input on command line.



Example as follows:





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

int
main()
{

string s1 = "Hello is that Tom? Are you ok Tom? Take Care tom!";
string s2 = "Tom";
string s3 = "William";

cout << "s1 = " << s1 << endl;

//Find s2 and replace by s3
bool flag = true;
while
(flag)
{

size_t found = s1.find(s2);
if
(found != string::npos)
{

s1.replace(found, s2.length(), s3);
}

else

{

flag = false;
}
}


cout << "s1 = " << s1 << endl;

return
0;
}






The output is as follows:







No comments:

Post a Comment