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

心已入冬 提交于 2019-12-23 21:19:32

问题


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


回答1:


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.)




回答2:


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 ; }


}


来源:https://stackoverflow.com/questions/9358718/similar-function-in-c-to-pythons-strip

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!