c++ c stl boost trim 函数
参考:
http://www.cplusplus.com/faq/sequences/strings/trim/
What's the best way to trim std::string http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
其中这个方案我喜欢:
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
// trim from start
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
BOOST 方案 :
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost::algorithm;
string str1(" hello world! ");
trim(str1);
// str1 is now "hello world!"
// Use trim_right() if only trailing whitespace is to be removed.
最剪短方案:
std::string s;
s.erase(s.find_last_not_of(" \n\r\t")+1);