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