/* Parse S into tokens separated by characters in DELIM.
If S is NULL, the saved pointer in SAVE_PTR is used as
the next starting point. For example:
char s[] = "-abc-=-def";
char *sp;
x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def"
x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL
x = strtok_r(NULL, "=", &sp); // x = NULL
// s = "abc\0-def\0"
*/
char *strtok_r(char *s, const char *delim, char **save_ptr) {
char *token;
if (s == NULL) s = *save_ptr;
/* Scan leading delimiters. */
s += strspn(s, delim);
if (*s == '\0')
return NULL;
/* Find the end of the token. */
token = s;
s = strpbrk(token, delim);
if (s == NULL)
/* This token finishes the string. */
*save_ptr = strchr(token, '\0');
else {
/* Terminate the token and make *SAVE_PTR point past it. */
*s = '\0';
*save_ptr = s + 1;
}
return token;
}
----------改----------
char *split(char *s, const char *delim,char **save_ptr)
{
stringresult;
char *token;
if (s == NULL) s = *save_ptr;
if (*s == ‘\0’)
return NULL;
/* Scan leading delimiters. */
string temp = s;
//s += strspn(s, delim);//替换
size_t pos_1 = temp.find_first_not_of(delim, 0 );
if (pos_1 == string::npos)
return NULL;
//(s应该指过去,temp应该记个temp[pos])
/* Find the end of the token. */
//token =s;
//s = strpbrk(token, delim);//替换
size_t pos_2 = temp.find_first_of(delim,pos_1)
if (pos_2 == string::npos)
/* This token finishes the string. */
result = s.substr(pos_1,);
strcpy(token, result.c_str());
*save_ptr = s + temp.size();
else {
/* Terminate the token and make *SAVE_PTR point past it. */
//*s = '\0';
result = temp.substr(pos_1,pos_2-pos_1);
strcpy(token, result.c_str());
*save_ptr = s + pos_2+1;
}
return token;
}