AIlaopo 发表于 2018-4-27 20:09:55

如何将一个string转换成vector

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

vector<string> str_vec;

请教大神如何将str中的每个单词存入到str_vec中

人造人 发表于 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
请按任意键继续. . .

BngThea 发表于 2018-4-27 21:35:33

遍历str用空格作为分割符依次添加
页: [1]
查看完整版本: 如何将一个string转换成vector