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