strtok() analogue in C++

元气小坏坏 提交于 2019-12-02 01:20:07

问题


I just can't find an algorithm to split the string into words by numerous delimiters. I know how to split a string by whitespace with istringtream and by single delimiter with getline. How can I connect them all.

For instance:

input: This -is-a!,string;
output:

This  
is  
a  
string

回答1:


#include <iostream>
#include <string>
#include <vector>

using namespace std;

void SplitToVector(vector<string> &v, string dlm, string src){
    string::size_type p, start=0, len=src.length(); 

    v.clear();
    start = src.find_first_not_of(dlm);
    p = src.find_first_of(dlm, start);
    while(p != string::npos){
        v.push_back(src.substr(start, p-start));
        start = src.find_first_not_of(dlm, p);
        p = src.find_first_of(dlm, start);
    }
    if(len>start)//rest
        v.push_back(src.substr(start, len - start));
}

int main(void){
    char input[256] = "This -is-a!,string;";
    vector<string> v;
    int i, size;

    SplitToVector(v, "-!,;", input);
    //cout << input << endl;
    size = v.size();
    for(i=0; i<size; i++)
        cout << v.at(i) << endl;
    return 0;
}



回答2:


Why not just #include <cstring> and use std::strtok() in your C++ program?




回答3:


I would recommend split in boost (string algorithm), see http://www.boost.org/doc/libs/1_53_0/doc/html/string_algo/usage.html#idp163440592.



来源:https://stackoverflow.com/questions/16807188/strtok-analogue-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!