This documentation is copyright © 1998-2001 Sandro Sigala <sandro@sigala.it>.
All rights reserved.
Released under the GNU General Public License.
strtok
Prototype
#include <string.h>
char *strtok(char *s, const char *delim);
Description
Decomposes the s
string into tokens, witch are sequences of characters
not occurring in the string delim
. The first call to strtok
should have the s
parameter set to a valid string pointer.
Subsequent calls should have the s
parameter set to NULL
; the
delim
parameter may be different for each call.
The strtok
returns a pointer to the next token,
or NULL
if there are no more tokens.
Please note that every call modifies the argument string s
(replaces
the delimiter after the token with a terminating null character).
Implementation
#include <string.h>
char *strtok(char *s, const char *delim)
{
const char *sp;
char *s_begin, *s_end;
static char *s_save = NULL;
s_begin = (s != NULL) ? s : s_save;
if (s_begin == NULL)
return NULL;
/* Skip the delimiters. */
for (;;) {
if (*s_begin == '\0') {
s_save = NULL;
return NULL;
}
for (sp = delim; *sp != '\0'; ++sp)
if (*s_begin == *sp) {
++s_begin;
break;
}
if (*sp == '\0')
break;
}
/* Find the token end. */
for (s_end = s_begin; *s_end != '\0'; ++s_end) {
for (sp = delim; *sp != '\0'; ++sp)
if (*s_end == *sp)
break;
if (*sp != '\0')
break;
}
if (*s_end != '\0')
*s_end++ = '\0';
s_save = s_end;
return s_begin;
}
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char buf[] = "dog:cat;mouse/bee:;horse", *p;
p = strtok(buf, ":;/");
while (p != NULL) {
printf("Token \"%s\"\n", p);
p = strtok(NULL, ":;/");
}
return EXIT_SUCCESS;
}
References
ISO C 9899:1990 7.11.5.8