boost字符串库简单使用

说明

写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结果

分割后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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值