找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 3106|回复: 1

【C++】std::string的一些学习记录

[复制链接]

55

主题

275

回帖

9354

积分

用户组: 管理员

UID
77
精华
16
威望
237 点
宅币
8219 个
贡献
251 次
宅之契约
0 份
在线时间
255 小时
注册时间
2014-2-22
发表于 2016-7-8 18:17:47 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有账号?立即注册→加入我们

×
原帖网址:http://www.m5home.com/bbs/thread-8848-1-1.html
未经允许请勿转发

前言:我本人一直很不待见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();
复制代码


回复

使用道具 举报

1111

主题

1651

回帖

7万

积分

用户组: 管理员

一只技术宅

UID
1
精华
244
威望
743 点
宅币
24241 个
贡献
46222 次
宅之契约
0 份
在线时间
2297 小时
注册时间
2014-1-26
发表于 2019-7-30 18:47:36 | 显示全部楼层
论stl的常见例子和应用。

说起来我踩过string的+运算符重载的坑,虽说我不会傻到用一个存储了十进制数字的string去 + 一个int,但我踩的其实是性能优化上的坑:用一个string去装一个string + 另一个string的结果,这个过程中的内存分配、构造、析构都很多。原本设想会很快的程序快不起来,搞得我很头疼。

从那以后我发现还有个叫“stringstream”的玩意儿用于使用类似cout的方式实现快速拼接字符串。
  1. ostringstream os;
  2. os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
  3. cout << os.str() << endl;
复制代码
https://stackoverflow.com/questi ... gstream-do/44782764
https://en.cppreference.com/w/cpp/io/basic_stringstream
回复 赞! 靠!

使用道具 举报

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-4-25 07:31 , Processed in 0.046108 second(s), 35 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

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