今天寫了 strtok 的範例:『如何分離網路 mac address』程式碼如下,大家一定會有疑問 strtok 第一次呼叫,第一參數輸入愈分離的字串,在 while 迴圈,則是輸入 NULL 呢?底下就來解析 strtok.c 的程式碼。
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
| /* * * Author : appleboy * Date : 2010.04.01 * Filename : strtok.c * */ #include "string.h" #include "stdlib.h" #include "stdio.h" int main() { char str[]= "00:22:33:4B:55:5A" ; char *delim = ":" ; char * pch; printf ( "Splitting string \"%s\" into tokens:\n" ,str); pch = strtok (str,delim); while (pch != NULL) { printf ( "%s\n" ,pch); pch = strtok (NULL, delim); } system ( "pause" ); 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
| __strtok_r( char *s, const char *delim, char **last) { char *spanp, *tok; int c, sc; if (s == NULL && (s = *last) == NULL) return (NULL); /* * Skip (span) leading delimiters (s += strspn(s, delim), sort of). */ cont: c = *s++; for (spanp = ( char *)delim; (sc = *spanp++) != 0;) { if (c == sc) goto cont; } if (c == 0) { /* no non-delimiter characters */ *last = NULL; return (NULL); } tok = s - 1; /* * Scan token (scan for delimiters: s += strcspn(s, delim), sort of). * Note that delim must have one NUL; we stop if we see that, too. */ for (;;) { c = *s++; spanp = ( char *)delim; do { if ((sc = *spanp++) == c) { if (c == 0) s = NULL; else s[-1] = '\0' ; *last = s; return (tok); } } while (sc != 0); } /* NOTREACHED */ } |
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
| /* Copyright (c) Microsoft Corporation. All rights reserved. */ #include <string.h> /* ISO/IEC 9899 7.11.5.8 strtok. DEPRECATED. * Split string into tokens, and return one at a time while retaining state * internally. * * WARNING: Only one set of state is held and this means that the * WARNING: function is not thread-safe nor safe for multiple uses within * WARNING: one thread. * * NOTE: No library may call this function. */ char * __cdecl strtok ( char *s1, const char *delimit) { static char *lastToken = NULL; /* UNSAFE SHARED STATE! */ char *tmp; /* Skip leading delimiters if new string. */ if ( s1 == NULL ) { s1 = lastToken; if (s1 == NULL) /* End of story? */ return NULL; } else { s1 += strspn (s1, delimit); } /* Find end of segment */ tmp = strpbrk (s1, delimit); if (tmp) { /* Found another delimiter, split string and save state. */ *tmp = '\0' ; lastToken = tmp + 1; } else { /* Last segment, remember that. */ lastToken = NULL; } return s1; } |
文章出處 : http://blog.wu-boy.com/2010/04/cc-%E5%88%87%E5%89%B2%E5%AD%97%E4%B8%B2%E5%87%BD%E6%95%B8%EF%BC%9Astrtok-network-mac-address-%E5%88%86%E5%89%B2/