xref: /csrg-svn/lib/libc/string/strtok.c (revision 35297)
124193Skre /*
2*35297Sbostic  * Copyright (c) 1988 Regents of the University of California.
334479Sbostic  * All rights reserved.
434479Sbostic  *
534479Sbostic  * Redistribution and use in source and binary forms are permitted
634831Sbostic  * provided that the above copyright notice and this paragraph are
734831Sbostic  * duplicated in all such forms and that any documentation,
834831Sbostic  * advertising materials, and other materials related to such
934831Sbostic  * distribution and use acknowledge that the software was developed
1034831Sbostic  * by the University of California, Berkeley.  The name of the
1134831Sbostic  * University may not be used to endorse or promote products derived
1234831Sbostic  * from this software without specific prior written permission.
1334831Sbostic  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
1434831Sbostic  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
1534831Sbostic  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
1624193Skre  */
1724193Skre 
1826538Sdonn #if defined(LIBC_SCCS) && !defined(lint)
19*35297Sbostic static char sccsid[] = "@(#)strtok.c	5.5 (Berkeley) 08/01/88";
2034479Sbostic #endif /* LIBC_SCCS and not lint */
2124193Skre 
22*35297Sbostic #include <stdio.h>
23*35297Sbostic 
2424193Skre char *
25*35297Sbostic strtok(s, delim)
26*35297Sbostic 	register char *s, *delim;
2724193Skre {
28*35297Sbostic 	register char *spanp;
29*35297Sbostic 	register int c, sc;
30*35297Sbostic 	char *tok;
31*35297Sbostic 	static char *last;
3224193Skre 
3324193Skre 
34*35297Sbostic 	if (s == NULL && (s = last) == NULL)
35*35297Sbostic 		return (NULL);
36*35297Sbostic 
37*35297Sbostic 	/*
38*35297Sbostic 	 * Skip (span) leading delimiters (s += strspn(s, delim), sort of).
39*35297Sbostic 	 */
40*35297Sbostic cont:
41*35297Sbostic 	c = *s++;
42*35297Sbostic 	for (spanp = delim; (sc = *spanp++) != 0;) {
43*35297Sbostic 		if (c == sc)
44*35297Sbostic 			goto cont;
4524193Skre 	}
4624193Skre 
47*35297Sbostic 	if (c == 0) {		/* no non-delimiter characters */
48*35297Sbostic 		last = NULL;
49*35297Sbostic 		return (NULL);
5024193Skre 	}
51*35297Sbostic 	tok = s - 1;
5224193Skre 
53*35297Sbostic 	/*
54*35297Sbostic 	 * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
55*35297Sbostic 	 * Note that delim must have one NUL; we stop if we see that, too.
56*35297Sbostic 	 */
57*35297Sbostic 	for (;;) {
58*35297Sbostic 		c = *s++;
59*35297Sbostic 		spanp = delim;
60*35297Sbostic 		do {
61*35297Sbostic 			if ((sc = *spanp++) == c) {
62*35297Sbostic 				if (c == 0)
63*35297Sbostic 					s = NULL;
64*35297Sbostic 				else
65*35297Sbostic 					s[-1] = 0;
66*35297Sbostic 				last = s;
67*35297Sbostic 				return (tok);
68*35297Sbostic 			}
69*35297Sbostic 		} while (sc != 0);
7024193Skre 	}
71*35297Sbostic 	/* NOTREACHED */
7224193Skre }
73