找回密码
 加入我们

QQ登录

只需一步,快速开始

搜索
查看: 6388|回复: 2

[分享] std::string的一些学习记录

[复制链接]

857

主题

2632

回帖

2

精华

管理员

此生无悔入华夏,  长居日耳曼尼亚。  

积分
36130
发表于 2016-7-8 17:57:15 | 显示全部楼层 |阅读模式
前言:我本人一直很不待见C++,但公司里的工程都是C++写的,不爽归不爽,还是被迫使用了一段时间。最近发现C++比起C来,某些地方还是有点优势的,比如字符串处理。C++里字符串类型很多,除了经典的CHAR*和WCHAR*,还有CString和std::string。个人不推荐用CString,因为这货是微软一家的,而std::string则是多平台兼容的。

一、使用std::string需要包含什么?
  1. #include <string>
复制代码

二、如何利用std::string和std::vector实现类似VB6的Split函数(根据标识符把字符串分割为多个子字符串)?
  1. #include <string>
  2. #include <vector>

  3. void SplitStdString(const std::string& s, std::vector<std::string>& v, const std::string& c)
  4. {
  5.         std::string::size_type pos1, pos2;
  6.         pos2 = s.find(c);
  7.         pos1 = 0;
  8.         while(std::string::npos != pos2)
  9.         {
  10.                 v.push_back(s.substr(pos1, pos2-pos1));
  11.                 pos1 = pos2 + c.size();
  12.                 pos2 = s.find(c, pos1);
  13.         }
  14.         if(pos1 != s.length())
  15.                 v.push_back(s.substr(pos1));
  16. }

  17. int main()
  18. {
  19.         char g_fw_policy1[]="4444;333;22;1";
  20.         char g_fw_policy2[]="a||bb||ccc||dddd";
  21.         std::vector<std::string> v;
  22.         std::string s;
  23.         //
  24.         s = g_fw_policy1;
  25.         SplitStdString(s,v,";");
  26.         for(long i=0;i<v.size();i++)
  27.                 puts(v.at(i).c_str());
  28.         //
  29.         v.clear();
  30.         s = g_fw_policy2;
  31.         SplitStdString(s,v,"||");
  32.         for(long i=0;i<v.size();i++)
  33.                 puts(v.at(i).c_str());
  34.         system("pause");
  35.         return 0;
  36. }
复制代码

三、如何把std::string转为CString
  1. CString cs = ss.c_str();
复制代码

四、如何把std::string里所有的A字符串都替换为B字符串?
  1. void ReplaceStdString(std::string &String, const std::string &strsrc, const std::string &strdst)
  2. {
  3.         std::string::size_type pos = 0;
  4.         std::string::size_type srclen = strsrc.size();
  5.         std::string::size_type dstlen = strdst.size();
  6.         while( (pos=String.find(strsrc, pos)) != std::string::npos )
  7.         {
  8.                 String.replace( pos, srclen, strdst );
  9.                 pos += dstlen;
  10.         }
  11. }
复制代码

评分

参与人数 1水晶币 +20 收起 理由
阿杰 + 20 很给力!

查看全部评分

1

主题

56

回帖

1

精华

贵宾会员

积分
2075
发表于 2016-7-8 18:56:59 | 显示全部楼层
支持一下,我学编程早期也是鼓捣C++,各种模板玩的不亦乐乎,到最后发现都是乱花渐欲迷人眼。
后来接触内核开始返璞归真,回归到C的怀抱,除非是逼不得已,否则再也不想用C++了。

2

主题

12

回帖

0

精华

铜牌会员

积分
217
发表于 2016-9-9 14:32:41 | 显示全部楼层
std::string确实好用,打算在开发驱动上使用它
您需要登录后才可以回帖 登录 | 加入我们

本版积分规则

快速回复 返回顶部 返回列表