Friday 4 March 2011

Removing all white-spaces from a string

Continuing on the same theme as the last post. What if all the spaces need to be stripped out from the input string:



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

using namespace
std;

string removeAllSpaces(const string& s)
{

string newStr(s);
bool
spacesLeft = true;

while
(spacesLeft)
{

int
pos = newStr.find(" ");
if
(pos != string::npos)
{

newStr.erase(pos, 1);
}

else

spacesLeft = false;
}


return
newStr;
}


int
main()
{

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

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

return
0;
}





The output is as follows:

No comments:

Post a Comment