Not sure about the idiom, but
char const WS[] = "..."; // whatever you consider WS
str.erase(0, str.find_first_not_of(WS));
str.erase(str.find_last_not_of(WS) + 1);
should do it. If you want your WS to be determined by a
function, like 'isspace' or whatnot, you need to write a
functor and remove/erase those for which the functor is true
or vice versa, keep those for which the functor yields
false... A bit more convoluted.
Yes and no. To begin with, the problem isn't adequately
specified; I use UTF-8 a lot, and the problem is a lot more
complex if you have to deal with multibyte encodings. And if
you're doing much text manipulation, you'll want to have such
functional objects in your tool kit anyway, at least for single
byte encodings. My own trim function is just:
std::string
leftTrim(
std::string const& s,
SetOfCharacter const&
toRemove )
{
return std::string(
std::find_if(
s.begin(), s.end(),
std::not1( toRemove.contains() ) ),
s.end() ) ;
}
std::string
rightTrim(
std::string const& s,
SetOfCharacter const&
toRemove )
{
return std::string(
s.begin(),
std::find_if(
s.rbegin(), s.rend(), std::not1
( toRemove.contains() ) )
.base() ) ;
}
std::string
trim(
std::string const& s,
SetOfCharacter const&
toRemove )
{
return leftTrim( rightTrim( s, toRemove ), toRemove ) ;
}
My SetOfCharacter class has a function contains() (with no
parameters) which returns the appropriate functional object, and
I have pre-defined instances of SetOfCharacter (actually
CharacterClass---a derived class with some more complex
constructors) for each of the standard isxxx functions (and then
some).
(FWIW: the UTF-8 versions look very similar; I've got some
special iterators, and the UTF-8 version of SetOfCharacter knows
how to handle what dereferencing them returns. So I end up
with:
std::string
leftTrim(
std::string const& original,
BasicSetOfCharacter const&
toRemove )
{
return std::string(
std::find_if( begin( original ),
end( original ),
std::not1( toRemove.contains() ) ).begin(),
original.end() ) ;
}
std::string
rightTrim(
std::string const& original,
BasicSetOfCharacter const&
toRemove )
{
return std::string(
original.begin(),
std::find_if( rbegin( original ),
rend( original ),
std::not1( toRemove.contains() ) )
.end() ) ;
}
std::string
trim(
std::string const& original,
BasicSetOfCharacter const&
toRemove )
{
return leftTrim( rightTrim( original, toRemove ), toRemove ) ;
}
std::string
trim(
std::string const& original )
{
return trim( original, CharacterData::space() ) ;
}
..)