没有什么能阻止您编写自己的 strtok
类似函数的代码:
#include <stdio.h>
#include <string.h>
static char *myStrTok (char *s, int c) {
static char *nextS = NULL; // Holds modified delimiter.
static int done = 1; // Flag to indicate all done.
// Initial case.
if (s != NULL) {
// Return NULL for empty string.
if (*s == '\0') { done = 1; return NULL; }
// Find next delimiter.
nextS = s;
while ((*nextS != c) && (*nextS != '\0')) nextS++;
done = (*nextS == '\0');
*nextS = '\0';
return s;
}
// Subsequent cases.
if (done) return NULL;
// Put delimiter back and find next one.
*nextS++ = c;
s = nextS;
while ((*nextS != c) && (*nextS != '\0')) nextS++;
done = (*nextS == '\0');
*nextS = '\0';
return s;
}
static int prt (char *s) {
char *s2 = myStrTok (s, ','); printf ("1: [%s]\n", s2);
s2 = myStrTok (NULL, ','); printf ("2: [%s]\n", s2);
s2 = myStrTok (NULL, ','); printf ("3: [%s]\n", s2);
s2 = myStrTok (NULL, ','); if (s2 != NULL) printf ("4: [%s]\n", s2);
printf ("==========\n");
}
int main (void) {
char x[] = "shankar,kumar,ooty"; char y[] = "ravi,,cbe";
prt (x); prt (y);
printf ("[%s] [%s]\n", x, y);
return 0;
}
这输出:
1: [shankar]
2: [kumar]
3: [ooty]
==========
1: [ravi]
2: []
3: [cbe]
==========
[shankar,kumar,ooty] [ravi,,cbe]
如你所愿。它只处理分隔符的单个字符,但在这种情况下似乎就足够了。