]> pd.if.org Git - pdclib/blob - functions/string/strtok.c
071f4f8607e4063f093674c3d81263f16d332793
[pdclib] / functions / string / strtok.c
1 /* $Id$ */
2
3 /* Release $Name$ */
4
5 /* strtok( char *, const char * )
6
7    This file is part of the Public Domain C Library (PDCLib).
8    Permission is granted to use, modify, and / or redistribute at will.
9 */
10
11 #include <_PDCLIB_aux.h>
12 #include <string.h>
13
14 char * strtok( char * _PDCLIB_restrict s1, const char * _PDCLIB_restrict s2 )
15 {
16     static char * tmp = NULL;
17     const char * p = s2;
18
19     if ( s1 != NULL )
20     {
21         /* new string */
22         tmp = s1;
23     }
24     else
25     {
26         /* old string continued */
27         if ( tmp == NULL )
28         {
29             /* No old string, no new string, nothing to do */
30             return NULL;
31         }
32         s1 = tmp;
33     }
34
35     /* skipping leading s2 characters */
36     while ( *p && *s1 )
37     {
38         if ( *s1 == *p )
39         {
40             /* found seperator; skip and start over */
41             ++s1;
42             p = s2;
43             continue;
44         }
45         ++p;
46     }
47
48     if ( ! *s1 )
49     {
50         /* no more to parse */
51         return ( tmp = NULL );
52     }
53
54     /* skipping non-s2 characters */
55     tmp = s1;
56     while ( *tmp )
57     {
58         p = s2;
59         while ( *p )
60         {
61             if ( *tmp == *p++ )
62             {
63                 /* found seperator; overwrite with '\0', position tmp, return */
64                 *tmp++ = '\0';
65                 return s1;
66             }
67         }
68         ++tmp;
69     }
70
71     /* parsed to end of string */
72     return ( tmp = NULL );
73 }
74
75 #ifdef TEST
76 #include <_PDCLIB_test.h>
77
78 int main()
79 {
80     char s[] = "_a_bc__d_";
81     BEGIN_TESTS;
82     TESTCASE( strtok( s, "_" ) == &s[1] );
83     TESTCASE( s[1] == 'a' );
84     TESTCASE( s[2] == '\0' );
85     TESTCASE( strtok( NULL, "_" ) == &s[3] );
86     TESTCASE( s[3] == 'b' );
87     TESTCASE( s[4] == 'c' );
88     TESTCASE( s[5] == '\0' );
89     TESTCASE( strtok( NULL, "_" ) == &s[7] );
90     TESTCASE( s[6] == '_' );
91     TESTCASE( s[7] == 'd' );
92     TESTCASE( s[8] == '\0' );
93     TESTCASE( strtok( NULL, "_" ) == NULL );
94     return TEST_RESULTS;
95 }
96 #endif