Python中有一个非常有用的函数,叫做 strip()。 C++中有类似的吗?
There is a very useful function in Python called strip(). Any similar ones in C++?
我用这个:
#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()); }
I use this:
没有任何内置的东西;我曾经使用类似以下的东西:
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 的版本。)
There's nothing built-in; I used to use something like the following:
which works pretty well. (I now have a significantly more complexversion which handles UTF-8 correctly.)
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) || (v==t) || (v==r) || (v==n)) { str.erase(str.begin()); v = std::string(1 ,str.front()); } v = std::string(1 , str.back()); while((v ==w) || (v==t) || (v==r) || (v==n)) { str.erase(str.end() - 1 ); v = std::string(1 , str.back()); } }
这是 Ferdi Kedef 提供的答案之上的,以使其更安全。
void strip(std::string& str) { if (str.length() == 0) { return; } auto start_it = str.begin(); auto end_it = str.rbegin(); while (std::isspace(*start_it)) { ++start_it; if (start_it == str.end()) break; } while (std::isspace(*end_it)) { ++end_it; if (end_it == str.rend()) break; } int start_pos = start_it - str.begin(); int end_pos = end_it.base() - str.begin(); str = start_pos <= end_pos ? std::string(start_it, end_it.base()) : ""; }
This is on top of the answer provided by Ferdi Kedef to make it safer.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
暂无简介
文章 0 评论 0
接受
发布评论
评论(4)
我用这个:
I use this:
没有任何内置的东西;我曾经使用类似以下的东西:
效果很好。 (我现在有一个更加复杂的
正确处理 UTF-8 的版本。)
There's nothing built-in; I used to use something like the following:
which works pretty well. (I now have a significantly more complex
version which handles UTF-8 correctly.)
这是 Ferdi Kedef 提供的答案之上的,以使其更安全。
This is on top of the answer provided by Ferdi Kedef to make it safer.