6 /* This version of Strtok differs from the regular ANSI strtok in that
7 * an empty token can be returned, and consecutive delimiters are not
8 * ignored like ANSI does. Example:
10 * Parse String = ",,mike,gleason,-West Interactive,402-573-1000"
14 * strtok 1=[mike] length=4
15 * strtok 2=[gleason] length=7
16 * strtok 3=[West Interactive] length=16
17 * strtok 4=[402] length=3
18 * strtok 5=[573] length=3
19 * strtok 6=[1000] length=4
22 * Strtok 1=[] length=0
23 * Strtok 2=[] length=0
24 * Strtok 3=[mike] length=4
25 * Strtok 4=[gleason] length=7
26 * Strtok 5=[] length=0
27 * Strtok 6=[West Interactive] length=16
28 * Strtok 7=[402] length=3
29 * Strtok 8=[573] length=3
30 * Strtok 9=[1000] length=4
35 Strtok(char *buf
, const char *delims
)
37 static char *p
= NULL
;
44 return (NULL
); /* No more tokens. */
46 for (start
= p
, end
= p
; ; end
++) {
48 p
= NULL
; /* This is the last token. */
51 if (strchr(delims
, (int) *end
) != NULL
) {
63 /* This is a bounds-safe version of Strtok, where you also pass a pointer
64 * to the token to write into, and its size. Using the example above,
65 * with a char token[8], you get the following. Notice that the token
66 * is not overrun, and is always nul-terminated:
68 * Strntok 1=[] length=0
69 * Strntok 2=[] length=0
70 * Strntok 3=[mike] length=4
71 * Strntok 4=[gleason] length=7
72 * Strntok 5=[] length=0
73 * Strntok 6=[West In] length=7
74 * Strntok 7=[402] length=3
75 * Strntok 8=[573] length=3
76 * Strntok 9=[1000] length=4
80 Strntok(char *dstTokenStart
, size_t tokenSize
, char *buf
, const char *delims
)
82 static char *p
= NULL
;
89 lim
= dst
+ tokenSize
- 1; /* Leave room for nul byte. */
96 return (-1); /* No more tokens. */
100 for (end
= p
; ; end
++) {
102 p
= NULL
; /* This is the last token. */
105 if (strchr(delims
, (int) *end
) != NULL
) {
110 if (dst
< lim
) /* Don't overrun token size. */
114 len
= (int) (dst
- dstTokenStart
); /* Return length of token. */
116 #if (STRN_ZERO_PAD == 1)
117 /* Pad with zeros. */
118 for (++dst
; dst
<= lim
; )
120 #endif /* STRN_ZERO_PAD */
127 #ifdef TESTING_STRTOK
131 main(int argc
, char **argv
)
140 fprintf(stderr
, "Usage: test \"buffer,with,delims\" <delimiters>\n");
143 strcpy(buf
, argv
[1]);
145 t
= strtok(buf
, argv
[2]);
149 printf("strtok %d=[%s] length=%d\n", i
, t
, (int) strlen(t
));
150 t
= strtok(NULL
, argv
[2]);
154 printf("------------------------------------------------\n");
155 strcpy(buf
, argv
[1]);
157 t
= Strtok(buf
, argv
[2]);
161 printf("Strtok %d=[%s] length=%d\n", i
, t
, (int) strlen(t
));
162 t
= Strtok(NULL
, argv
[2]);
166 printf("------------------------------------------------\n");
167 strcpy(buf
, argv
[1]);
169 tokenLen
= Strntok(token
, sizeof(token
), buf
, argv
[2]);
173 printf("Strntok %d=[%s] length=%d\n", i
, token
, tokenLen
);
174 tokenLen
= Strntok(token
, sizeof(token
), NULL
, argv
[2]);
176 } while (tokenLen
>= 0);