JUST DO IT ~

我只想当个程序员

c++ c stl boost trim 函数

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 &ltrim(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);
 

posted on 2015-03-20 09:39 小高 阅读(1896) 评论(0)  编辑  收藏 所属分类: C


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2015年3月>
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

统计

常用链接

留言簿(3)

随笔分类(352)

收藏夹(19)

关注的blog

手册

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜