C++中的类似函数是Python的strip()?

MBZ*_*MBZ 3 c++ string strip

Python中有一个非常有用的函数叫做strip().C++中有类似的吗?

小智 9

我用这个:

#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());
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*nze 5

没有任何内置的东西; 我过去经常使用以下内容:

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 );
}
Run Code Online (Sandbox Code Playgroud)

哪个效果很好.(我现在有一个更复杂的版本,可以正确处理UTF-8.)