strtok函数原型:
#include <string.h>
char* strtok(char* str, const char* delimiters);
模拟实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| char* Strtok(char* str, const char* delim) { static char* p = NULL; if (str) { p = str; } else if (!p) { return NULL; } str = p + strspn(p, delim); p = str + strcspn(str, delim); if (p == str) { p = NULL; return NULL; } if (*p) { *p = '\0'; ++p; } else { p = NULL; } return str; }
int main() { char str[] = "My name is---ran jia hao---"; char* pch; pch = Strtok(str, " -"); while (pch) { printf("%s\n", pch); pch = Strtok(NULL, " -"); } return 0; }
|
源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| char* strtok_r(char* string_org, const char* demial) { static unsigned char* last; unsigned char* str; const unsigned char* ctrl = (const unsigned char*)demial;
unsigned char map[32]; for (int count = 0; count < 32; count++) { map[count] = 0; }
do { map[*ctrl >> 3] |= (1 << (*ctrl & 7)); } while (*ctrl++);
if (string_org) { str = (unsigned char*)string_org; } else { str = last; }
while ((map[*str >> 3] & (1 << (*str & 7))) && *str) { str++; }
string_org = (char*)str;
for (; *str; str++) { if (map[*str >> 3] & (1 << (*str & 7))) { *str++ = '\0'; break; } } last = str; if (string_org == (char*)str) { return NULL; } else { return string_org; } }
|