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:

1 comment:

  1. Or, you know, you -could-

    #include

    /* isspace in cctype may be a macro, so isn't safe to use */

    bool is_space(char c) { return c == ' '; }

    void remove_space(string &s) {

    remove_if(s.begin(), s.end(), is_space);

    }

    ReplyDelete