removing leading+trailing dashes from strings
Mar 10, 2011 at 12:57am UTC
Very good speed optimized code.
I mean size optimized.
Thank you.
Mar 17, 2011 at 8:30pm UTC
It seems to me that there're bugs in the last post:
1 2 3 4 5 6 7 8 9 10
std::string remove_dashes( const std::string& src )
{
std::string::size_type first_non_dash = src.find_first_not_of( '-' );
if ( first_non_dash == std::string::npos ) return src; // return std::string();
std::string::size_type last_non_dash = src.find_last_not_of( '-' );
if ( last_non_dash == first_non_dash ) return std::string(); // kick this
return std::string( src, first_non_dash, last_non_dash - first_non_dash ); // + 1);
}
==>fixed:
1 2 3 4 5 6 7 8 9
std::string remove_dashes( const std::string& src )
{
std::string::size_type first_non_dash = src.find_first_not_of( '-' );
if ( first_non_dash == std::string::npos ) return std::string(); // all dashes
std::string::size_type last_non_dash = src.find_last_not_of( '-' );
return std::string( src, first_non_dash, last_non_dash - first_non_dash + 1 );
}
==>optimized:
1 2 3 4 5 6 7 8 9 10 11
void S::F_CutDash(string& s)
{
if (s.find('-' ) != string::npos) { // rather seldom
int i = s.find_first_not_of('-' );
if (i == string::npos)
s.erase();
else
s.assign(s, i, s.find_last_not_of('-' ) - i + 1);
}
}
Last edited on Mar 18, 2011 at 10:21pm UTC
Topic archived. No new replies allowed.