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
#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;
}
Why not just #include <cstring> and use std::strtok() in your C++ program?
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