说明
写c++程序的时候,虽然std::string有数百余函数,然而仍不能满足很多需要,对字符串的处理不如其他语言方便简洁(例如字符串的分割、字符串转换到大写字母的函数),Boost C++ 库试图弥补这一缺憾,这里列出boost字符串库我常用到的地方。
参考:
boost::algorithm(字符串算法库)
用法
头文件添加
#include<boost/algorithm/string.hpp>
- 1
大小写转换
std::string s("hello string");
boost::to_upper(s);//装换为大写
std::string str1=boost::to_lower_copy(s);//小写转换并赋值
std::string str2=boost::to_upper_copy(s);//大写转换并赋值
- 1
- 2
- 3
- 4
字符串分割
std::string s("hello,123,1,2,3,456;string");
std::vector<std::string> sv;
boost::split(sv , s, boost::is_any_of(","),boost::token_compress_on);
/**************************************************************
* 第三个选的设置,可以压缩多个第二个参数,
* token_compress_on :打开压缩功能
* tock_compreess_off: 关闭压缩功能
**************************************************************/
- 1
- 2
- 3
分割后sv结果
去掉字符串两边空格
std::string s(" test string ");
boost::trim_left(s);//去掉字符串左边空格
boost::trim_right(s);//去掉字符串右边空格
std::cout<<s<<std::endl;
//输出为:test string
//现在s="test string"
- 1
- 2
- 3
- 4
- 5
- 6
扩展:
//boost::trim_left_copy(s)和boost::trim_right_copy(s)表示去掉后赋值
- 1
std::string s(" test string ");
std::string sn;
sn = boost::trim_left_copy(s);
std::cout<<s<<std::endl;
std::cout<<sn<<std::endl;
- 1
- 2
- 3
- 4
- 5
输出:
test string
test string
- 1
- 2
替换字符串
replace_first()
从头找到第一个匹配的字符串,将其替换为给定的另外一个字符串
string str1("hello world!");
replace_first(str1, "hello", "Hello");
// str1 = "Hello world!"
- 1
- 2
- 3
replace_first_copy
从头找到第一个匹配的字符串,将其替换为给定的另外一个字符串,并且赋值给另一个字符串
string str1("hello world!");
string str2;
str2 = replace_first_copy(str1, "hello", "Hello"); // str2 = "Hello world!"
- 1
- 2
- 3