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

问题描述 投票:3回答:2

Python中有一个非常有用的函数,称为strip()。 C ++中是否有类似的代码?

c++ string strip
2个回答
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 );
}

效果很好。 (我现在的情况要复杂得多可以正确处理UTF-8的版本。)


0
投票
void strip(std::string &str ){
if  (!(str.length() == 0)) {
auto w = std::string(" ") ;
auto n = std::string("\n") ;
auto r = std::string("\t") ;
auto t = std::string("\r") ;
auto v = std::string(1 ,str.front()); 
while((v == w) or(v==t)or(v==r)or(v==n)) {str.erase(str.begin()) ;v = std::string(1 ,str.front()); }
v = std::string(1 , str.back()) ; 
while((v ==w) or(v==t)or(v==r)or(v==n)) {str.erase(str.end() - 1 )  ;v = std::string(1 , str.back()) ;}
std::cout << str ; }

}

© www.soinside.com 2019 - 2024. All rights reserved.