Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Similar function in C++ to Python's strip()?

Tags:

c++

string

strip

There is a very useful function in Python called strip(). Any similar ones in C++?

like image 709
MBZ Avatar asked Feb 20 '12 09:02

MBZ


2 Answers

There's nothing built-in; I used to use something like the following:

template <std::ctype_base::mask mask>
class IsNot
{
    std::locale myLocale;       // To ensure lifetime of facet...
    std::ctype<char> const* myCType;
public:
    IsNot( std::locale const& l = std::locale() )
        : myLocale( l )
        , myCType( &std::use_facet<std::ctype<char> >( l ) )
    {
    }
    bool operator()( char ch ) const
    {
        return ! myCType->is( mask, ch );
    }
};

typedef IsNot<std::ctype_base::space> IsNotSpace;

std::string
trim( std::string const& original )
{
    std::string::const_iterator right = std::find_if( original.rbegin(), original.rend(), IsNotSpace() ).base();
    std::string::const_iterator left = std::find_if(original.begin(), right, IsNotSpace() );
    return std::string( left, right );
}

which works pretty well. (I now have a significantly more complex version which handles UTF-8 correctly.)

like image 137
James Kanze Avatar answered Oct 02 '22 20:10

James Kanze


I use this:

#include <string>
#include <cctype>

std::string strip(const std::string &inpt)
{
    auto start_it = inpt.begin();
    auto end_it = inpt.rbegin();
    while (std::isspace(*start_it))
        ++start_it;
    while (std::isspace(*end_it))
        ++end_it;
    return std::string(start_it, end_it.base());
}
like image 20
Ferdi Kedef Avatar answered Oct 02 '22 20:10

Ferdi Kedef