Python中有一个非常有用的函数叫strip()。 C ++中有类似的吗?
答案 0 :(得分: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的版本。)
答案 1 :(得分:1)
我用这个:
#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());
}
答案 2 :(得分: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 ; }
}