鱼C论坛

 找回密码
 立即注册
查看: 2961|回复: 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 | 显示全部楼层
#include <iostream>
#include <vector>
#include <string>

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

        int pos_begin = 0;
        int pos_end = 0;

        do
        {
                pos_end = src.find(pattern, pos_begin);
                dest.push_back(src.substr(pos_begin, pos_end - pos_begin));
                pos_begin = pos_end + pattern.size();
        }
        while(pos_end != -1);
}

int main()
{
        std::vector<std::string> v;
        std::string s("the quick red fox jumps over the slow red turtle");
        
        split(v, s, " ");
        for(auto iter = v.begin(); iter != v.end(); ++iter)
        {
                std::cout << *iter << std::endl;
        }

        std::cout << std::endl;
        
        split(v, s, " red ");
        for(auto iter = v.begin(); iter != v.end(); ++iter)
        {
                std::cout << *iter << std::endl;
        }

        return 0;
}
the
quick
red
fox
jumps
over
the
slow
red
turtle

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

使用道具 举报

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-10-1 21:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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