C++replace_all strip函数

本文介绍了一种在C++中实现的字符串替换方法,该方法能够高效地将字符串中的指定子串全部替换成新的子串,并提供了一个去除字符串两端空白字符或指定字符的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. // replace all occurance of t in s to w  
  2. void replace_all(std::string & s, std::string const & t, std::string const & w)  
  3. {  
  4.   string::size_type pos = s.find(t), t_size = t.size(), r_size = w.size();  
  5.   while(pos != std::string::npos){ // found   
  6.     s.replace(pos, t_size, w);   
  7.     pos = s.find(t, pos + r_size );   
  8.   }  
  9. }  
  10.   
  11. string strip(string const & s, char c = ' ')  
  12. {  
  13.   string::size_type a = s.find_first_not_of(c);  
  14.   string::size_type z = s.find_last_not_of(c);  
  15.   if(a == string::npos){  
  16.     a = 0;  
  17.   }  
  18.   
  19.   if(z == string::npos){  
  20.     z = s.size();  
  21.   }  
  22.   return s.substr(a, z);  
  23. }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值