Abstract
Use the example for strtok.
Introduction
Use environment: 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 }
Results
Download the complete program
Strtok.7z
Remark
Csie-tw asked why strtok (null, del) should be used for the second call. This is a good question, let's take a look at how Microsoft implements 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
10 * Warning: function is not thread-safe nor safe for multiple uses
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 + = Strspns (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 }
It can be found that when S1 is null, it will use the static char * pointer + 1 character pair to search for keys, if S1! = NULL, it is the first time strtok () is used ().