鱼C论坛

 找回密码
 立即注册
查看: 2717|回复: 2

如何将一个string转换成vector

[复制链接]
发表于 2018-4-27 20:09:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

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

x
string str = "the quick red fox jumps over the slow red turtle";

vector<string> str_vec;

请教大神如何将str中的每个单词存入到str_vec中
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-4-27 21:30:52 | 显示全部楼层
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>

  4. void split(std::vector<std::string> &dest, std::string src, std::string pattern)
  5. {
  6.         dest.clear();

  7.         int pos_begin = 0;
  8.         int pos_end = 0;

  9.         do
  10.         {
  11.                 pos_end = src.find(pattern, pos_begin);
  12.                 dest.push_back(src.substr(pos_begin, pos_end - pos_begin));
  13.                 pos_begin = pos_end + pattern.size();
  14.         }
  15.         while(pos_end != -1);
  16. }

  17. int main()
  18. {
  19.         std::vector<std::string> v;
  20.         std::string s("the quick red fox jumps over the slow red turtle");
  21.        
  22.         split(v, s, " ");
  23.         for(auto iter = v.begin(); iter != v.end(); ++iter)
  24.         {
  25.                 std::cout << *iter << std::endl;
  26.         }

  27.         std::cout << std::endl;
  28.        
  29.         split(v, s, " red ");
  30.         for(auto iter = v.begin(); iter != v.end(); ++iter)
  31.         {
  32.                 std::cout << *iter << std::endl;
  33.         }

  34.         return 0;
  35. }
复制代码

  1. the
  2. quick
  3. red
  4. fox
  5. jumps
  6. over
  7. the
  8. slow
  9. red
  10. turtle

  11. the quick
  12. fox jumps over the slow
  13. turtle
  14. 请按任意键继续. . .
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-4-27 21:35:33 From FishC Mobile | 显示全部楼层
遍历str用空格作为分割符依次添加
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-2 11:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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