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方法。
第二种自己写。
各有好处

第一种:

  1. #include <boost/algorithm/string.hpp>  
  2. using namespace std;  
  3. using namespace boost::algorithm;  
  4.   
  5. string str1(" hello world! ");  
  6. trim(str1);  


另外网址1还提供了第二种方法的稍微有点不同的想法

  1. #include <algorithm>   
  2. #include <functional>   
  3. #include <cctype>  
  4. #include <locale>  
  5.   
  6. // trim from start  
  7. static inline std::string <rim(std::string &s) {  
  8.         s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<intint>(std::isspace))));  
  9.         return s;  
  10. }  
  11.   
  12. // trim from end  
  13. static inline std::string &rtrim(std::string &s) {  
  14.         s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<intint>(std::isspace))).base(), s.end());  
  15.         return s;  
  16. }  
  17.   
  18. // trim from both ends  
  19. static inline std::string &trim(std::string &s) {  
  20.         return ltrim(rtrim(s));  
  21. }  





第二种:

    1. #include <string>  
    2.  #include <vector>  
    3.  #include <algorithm>     
    4.  #include <functional>     
    5.       
    6.  using namespace std;  
    7.    
    8.    
    9.  inline string&  lTrim(string   &ss)     
    10. {     
    11.     string::iterator   p=find_if(ss.begin(),ss.end(),not1(ptr_fun(isspace)));     
    12.     ss.erase(ss.begin(),p);     
    13.     return  ss;     
    14. }     
    15.   
    16. inline  string&  rTrim(string   &ss)     
    17. {     
    18.     string::reverse_iterator  p=find_if(ss.rbegin(),ss.rend(),not1(ptr_fun(isspace)));     
    19.     ss.erase(p.base(),ss.end());     
    20.     return   ss;     
    21. }     
    22.   
    23. inline   string&   trim(string   &st)     
    24. {     
    25.     lTrim(rTrim(st));     
    26.     return   st;     
    27. }     

posted on 2012-09-05 19:09  Hugoo  阅读(2758)  评论(0)    收藏  举报