string rtrim ?

  • Thread starter jose luis fernandez diaz
  • Start date
J

jose luis fernandez diaz

Hi,

This is my rtrim version:


inline void rtrim(string *ptr_s)
{
string::reverse_iterator rit= ptr_s->rbegin();
while(rit != ptr_s->rend() && *rit==' ') ptr_s->erase((++rit).base());
}

Can anyone give any hint to improve it ?

Thanks,
Jose Luis
 
A

Andre Kostur

(e-mail address removed) (jose luis fernandez diaz) wrote in
Hi,

This is my rtrim version:


inline void rtrim(string *ptr_s)
{
string::reverse_iterator rit= ptr_s->rbegin();
while(rit != ptr_s->rend() && *rit==' ')
ptr_s->erase((++rit).base());
}

Can anyone give any hint to improve it ?

Thanks,
Jose Luis

void rtrim(string & str)
{
str.erase(str.find_last_not_of(" "), str.end());
}


?
 
R

Ronald Landheer-Cieslak

jose said:
Hi,

This is my rtrim version:


inline void rtrim(string *ptr_s)
{
string::reverse_iterator rit= ptr_s->rbegin();
while(rit != ptr_s->rend() && *rit==' ') ptr_s->erase((++rit).base());
}

Can anyone give any hint to improve it ?

Thanks,
Jose Luis
Here's a few ideas:
1. pass a reference in stead of a pointer - you don't have to orry about
NULL in that case
2. make it a template function - that way, you're not restricted to just
strings but can use the same function on things that have a similar
interface
3. find the last non-space with find_last_not_of and call erase only
once with that information
4. search for more than just spaces - i.e. any white space (horizontal &
tabs, nelines, carriage returns, etc.) or (if you go with point 2.)
supply a second tempalte argument with a list of whitespaces that
defaults to the one you want to use by default
<untested_code>
template <typename C, const C whitespace = " \t\n\r">
inline void rtrim(std::basic_string<C> & s);
</untested_code>
HTH

rlc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,174
Messages
2,570,941
Members
47,476
Latest member
blackwatermelon

Latest Threads

Top