Since string‘s split function is not naturally provided in C++, we must implement it by ourselves. Here is a simple implementation of split based on strtok.
vector<string> split(const string &str, const string &sep)
{
char *cstr = new char[str.size()+1];
char *csep = new char[sep.size()+1];
strcpy(cstr, str.c_str());
strcpy(csep, sep.c_str());
char *csubstr = strtok(cstr, csep);
vector<string> res;
while (csubstr != NULL)
{
res.push_back(csubstr);
csubstr = strtok(NULL, csep);
}
delete[] cstr;
delete[] csep;
return res;
}To successfully use it, please include following headers:
#include <vector> // necessary for split, vector #include <string> // necessary for split, string #include <cstring> // necessary for split, strcpy, strtok
A simple implementation of string split in C++
原文:http://blog.csdn.net/jsc0218/article/details/19818537