C++实现trim()函数
此处参考两处:
1、http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
2、http://www.cppblog.com/cc/archive/2007/08/09/29667.html
第一种采用boost::algorithm::trim方法。
第二种自己写。
各有好处
第一种:
- #include <boost/algorithm/string.hpp>
- using namespace std;
- using namespace boost::algorithm;
- string str1(" hello world! ");
- trim(str1);
另外网址1还提供了第二种方法的稍微有点不同的想法
- #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));
- }
第二种:
- #include <string>
- #include <vector>
- #include <algorithm>
- #include <functional>
- using namespace std;
- inline string& lTrim(string &ss)
- {
- string::iterator p=find_if(ss.begin(),ss.end(),not1(ptr_fun(isspace)));
- ss.erase(ss.begin(),p);
- return ss;
- }
- inline string& rTrim(string &ss)
- {
- string::reverse_iterator p=find_if(ss.rbegin(),ss.rend(),not1(ptr_fun(isspace)));
- ss.erase(p.base(),ss.end());
- return ss;
- }
- inline string& trim(string &st)
- {
- lTrim(rTrim(st));
- return st;
- }
浙公网安备 33010602011771号