Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

leading and trailing spaces

15 views
Skip to first unread message

Chris

unread,
Apr 12, 2002, 7:40:23 AM4/12/02
to
Hi,

maybe someone could tell me what command I have to use for remove leading
and trailing spaces.

Is it trim()? Is there any #include or using neccesary?

Thanks

Cheers

Chris


David Hilsee

unread,
Apr 12, 2002, 9:06:04 AM4/12/02
to

"Chris" <c...@coelle.net> wrote in message
news:HIzt8.24639$vc3....@news-server.bigpond.net.au...

There is no standard function to do this, but writing the function is
trivial:

void trim( std::string& s )
{
std::string::reverse_iterator rit = s.rbegin();

while( rit != s.rend() && isspace(*rit) ) ++rit;

s.erase( rit.base(), s.end() );

std::string::iterator it = s.begin();

while( it != s.end() && isspace(*it) ) ++it;

s.erase( s.begin(), it );
}

--
David Hilsee


Daniel T.

unread,
Apr 12, 2002, 9:15:24 AM4/12/02
to
"Chris" <c...@coelle.net> wrote:

>maybe someone could tell me what command I have to use for remove leading
>and trailing spaces.
>
>Is it trim()? Is there any #include or using neccesary?

You have to write trim yourself...

Here is what I did:


#include <string>

const std::string whiteSpaces( " \f\n\r\t\v" );

void trimRight( std::string& str,
const std::string& trimChars = whiteSpaces )
{
std::string::size_type pos = str.find_last_not_of( trimChars );
str.erase( pos + 1 );
}

void trimLeft( std::string& str,
const std::string& trimChars = whiteSpaces )
{
std::string::size_type pos = str.find_first_not_of( trimChars );
str.erase( 0, pos );
}

void trim( std::string& str, const std::string& trimChars = whiteSpaces )
{
trimRight( str, trimChars );
trimLeft( str, trimChars );
}

0 new messages