第1个回答 2017-09-30
给你3种实现:
int split(char **arr, char *str, const char *delim){
char *s = strtok(str, delim);
int c=0;
while (s!=NULL) {
*arr++ = s;
s = strtok(NULL, delim);
c++;
}
return c;
}
vector<string> split(char *str, const char *delim) {
vector<string> elems;
char *s = strtok(str, delim);
while (s!=NULL) {
elems.push_back(s);
s = strtok(NULL, delim);
}
return elems;
}
vector<string> split(const string& s, const string& delim) {
vector<std::string> elems;
size_t pos = 0;
size_t len = s.length();
size_t delim_len = delim.length();
while (pos < len) {
int find_pos = s.find(delim, pos);
if (find_pos < 0) {
elems.push_back(s.substr(pos, len - pos));
break;
}
elems.push_back(s.substr(pos, find_pos - pos));
pos = find_pos + delim_len;
}
return elems;
}本回答被提问者采纳