分隔和截断字符串, boost string algorithm library中的split和trim
http://www.boost.org/doc/libs/1_46_1/doc/html/string_algo.html
这个库是个 headers only library 这个库提供了STL没有提供的 string-related算法, 但是实现做到了可以用在任何 character 的 container上
split
在写在线状态的改造时候要把一个字符串中描述的几种类型拆出来, 引发了这个问题, 去标准库里找了也没找到, 后来在boost库中找到了string_algo这个库, 以下是我写的一个使用split的例子
1 #include <boost/algorithm/string.hpp>
2 #include <iostream>
3 #include <string>
4 #include <vector>
5 using namespace boost::algorithm;
6 using namespace std;
7 int main(){
8 string str("miss,you.just.call_to,say,I~love~you");
9 vector<string> strVec;
10 split(strVec, str, is_any_of(",."));
11 vector<string>::iterator it = strVec.begin();
12 for (; it!=strVec.end(); it++){
13 cout << *it << endl;
14 }
15 return 0;
16 }
运行的结果就是都拆出来了 miss you just call to say I~love~you, 注意分隔符是,. 没有用~, 所有后面的I~love~you没有拆
头文件统一的话就用的#include<boost/algorithm/string.hpp> 9, 10行就是split的使用方式
2. 我们用的头文件是 boost/algorithm/string.hpp, 这个头文件只用来包括其他具体的头文件, 在 algorithm/string目录下如 split的就是 boost/algorithm/string/split.hpp, 里面定义了几个函数模板, 应该说这里面全是函数模板, 另外还可以看到, 这就是headers only library
trim
在写群聊中有遇到去掉一个string当中的空格,std中没有这样的算法,在boost::string_algo中找到了trim, 但它只能去除头尾,这个也很有用, 头文件是 <boost/algorithm/string/trim.hpp> 或<boost/algorithm/string.hpp>, 写了一些trim的测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
注意trim是一系列的函数,有最普通的默认去空格的trim, 也有指定去什么的trim_if, trim_left_if, 这是直接在参数指定的string上操作,也有把结果单独生成一个string的trim_copy_if, trim_left_copy_if
boost库在unix下的安装文档, http://www.boost.org/doc/libs/1_52_0/more/getting_started/unix-variants.html, 只需要简单的执行脚本就行了,会编译链接生成相应的库,且用头文件拷到相关的目录, 我自己在运行那个./bootrap脚本的时候开始老不成功,后来 google了一下是因为其要运行的 tools/..../build.sh没有 chmod +x