C++split的替代方法

等我发现更好的方式再回来。

1.stream流

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

vector<string> split(string s,char token){
    stringstream iss(s);
    string word;
    vector<string> vs;
    while(getline(iss,word,token)){
        vs.push_back(word);
    }
    return vs;
}


int main()
{
    string s1 = "aaa,sss,ddd,fff";
    vector<string> s2 = split(s1, ',');
    cout << s1;
    for(int i=0;i<s2.size();i++)
    {
        cout<<s2[i]<<endl;
    }
    system("pause");
    return 0;
}

2.字符串切割

int split_string(const std::string& s, std::vector<std::string>& v, const std::string& c)
{
    std::string::size_type pos1, pos2;
    pos2 = s.find(c);
    pos1 = 0;
    while (std::string::npos != pos2)
    {
        v.push_back(s.substr(pos1, pos2 - pos1));

        pos1 = pos2 + c.size();
        pos2 = s.find(c, pos1);
    }
    if (pos1 != s.length())
        v.push_back(s.substr(pos1));
    return 0;
}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-12 01:40:05       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-12 01:40:05       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-12 01:40:05       87 阅读
  4. Python语言-面向对象

    2024-03-12 01:40:05       96 阅读

热门阅读

  1. Go语言中,如何调用C++的dll文件

    2024-03-12 01:40:05       48 阅读
  2. Python中输入输出函数input和print用法

    2024-03-12 01:40:05       39 阅读
  3. 【Spring Boot单元测试】讲解

    2024-03-12 01:40:05       45 阅读