(筆記) 如何使用strtok()? (C/C++) (C)

Abstract
strtok()的簡單使用範例。

Introduction
使用環境 : Visual Studio 2008

strtok.c / C

1 /* 
2 (C) OOMusou 2009 http://oomusou.cnblogs.com
3 
4 Filename    : strtok.c
5 Compiler    : Visual C++ 9.0
6 Description : Demo how to use strtok() in C
7 Release     : 05/09/2009 1.0
8 */
9 #include <stdio.h>
10 #include <string.h>
11 
12 int main() {
13   char str[] = "Hello,World";
14   const char *del = ",";
15   char *s = strtok(str, del);
16 
17   while(s != NULL) {
18     printf("%s\n", s);
19     s = strtok(NULL, del);
20   }
21 
22   return 0;
23 }


執行結果

strtok

完整程式碼下載
strtok.7z

Remark
csie-tw問到,為什麼第二次呼叫時,要使用strtok(NULL, del),這是一個很好的問題,所謂『有code有真相』,來看看Microsoft怎麼實作strtok()。

https://research.microsoft.com/en-us/um/redmond/projects/invisible/src/crt/strtok.c.htm

1 /* Copyright (c) Microsoft Corporation. All rights reserved. */
2 
3 #include <string.h>
4 
5 /* ISO/IEC 9899 7.11.5.8 strtok. DEPRECATED.
6  * Split string into tokens, and return one at a time while retaining state
7  * internally.
8  *
9  * WARNING: Only one set of state is held and this means that the
10  * WARNING: function is not thread-safe nor safe for multiple uses within
11  * WARNING: one thread.
12  *
13  * NOTE: No library may call this function.
14  */
15 
16 char * __cdecl strtok(char *s1, const char *delimit)
17 {
18     static char *lastToken = NULL; /* UNSAFE SHARED STATE! */
19     char *tmp;
20 
21     /* Skip leading delimiters if new string. */
22     if ( s1 == NULL ) {
23         s1 = lastToken;
24         if (s1 == NULL)         /* End of story? */
25             return NULL;
26     } else {
27         s1 += strspn(s1, delimit);
28     }
29 
30     /* Find end of segment */
31     tmp = strpbrk(s1, delimit);
32     if (tmp) {
33         /* Found another delimiter, split string and save state. */
34         *tmp = '\0';
35         lastToken = tmp + 1;
36     } else {
37         /* Last segment, remember that. */
38         lastToken = NULL;
39     }
40 
41     return s1;
42 }


可以發現,當S1為NULL時,他會使用lastToken這個static char *這個pointer+1繼續搜尋,若S1 != NULL,則當成第一次使用strtok()。

posted on 2009-05-10 03:06  真 OO无双  阅读(27157)  评论(3编辑  收藏  举报

导航