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