Showing posts with label String Replace. Show all posts
Showing posts with label String Replace. Show all posts

Tuesday, 1 March 2011

Removing Multiple White-spaces from a string

A simple program to remove an arbitrary number of white spaces in between words. Program as follows:




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

using namespace
std;

bool
removeDoubleSpaces(string& s)
{

bool
found = true;

int
i = s.find(" "); //Search for 2 spaces
if(i != string::npos)
{

s.replace(i, 2, " ");
}

else

found = false;

return
found;
}


string removeMultipleSpaces(const string& s)
{

string newStr(s);
bool
found = true;

while
(found)
{

found = removeDoubleSpaces(newStr);
}


return
newStr;
}


int
main()
{

string aString("This string has multiple spaces problem!");

cout<<"Original : "<<aString<<endl;
cout<<"Modified : "<<removeMultipleSpaces(aString)<<endl;

return
0;
}




The output is as follows:

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: