xref: /csrg-svn/lib/libc/string/strtok.c (revision 42181)
124193Skre /*
235297Sbostic  * 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*42181Sbostic static char sccsid[] = "@(#)strtok.c	5.6 (Berkeley) 05/17/90";
2034479Sbostic #endif /* LIBC_SCCS and not lint */
2124193Skre 
22*42181Sbostic #include <stddef.h>
23*42181Sbostic #include <string.h>
2435297Sbostic 
2524193Skre char *
2635297Sbostic strtok(s, delim)
2735297Sbostic 	register char *s, *delim;
2824193Skre {
2935297Sbostic 	register char *spanp;
3035297Sbostic 	register int c, sc;
3135297Sbostic 	char *tok;
3235297Sbostic 	static char *last;
3324193Skre 
3424193Skre 
3535297Sbostic 	if (s == NULL && (s = last) == NULL)
3635297Sbostic 		return (NULL);
3735297Sbostic 
3835297Sbostic 	/*
3935297Sbostic 	 * Skip (span) leading delimiters (s += strspn(s, delim), sort of).
4035297Sbostic 	 */
4135297Sbostic cont:
4235297Sbostic 	c = *s++;
4335297Sbostic 	for (spanp = delim; (sc = *spanp++) != 0;) {
4435297Sbostic 		if (c == sc)
4535297Sbostic 			goto cont;
4624193Skre 	}
4724193Skre 
4835297Sbostic 	if (c == 0) {		/* no non-delimiter characters */
4935297Sbostic 		last = NULL;
5035297Sbostic 		return (NULL);
5124193Skre 	}
5235297Sbostic 	tok = s - 1;
5324193Skre 
5435297Sbostic 	/*
5535297Sbostic 	 * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
5635297Sbostic 	 * Note that delim must have one NUL; we stop if we see that, too.
5735297Sbostic 	 */
5835297Sbostic 	for (;;) {
5935297Sbostic 		c = *s++;
6035297Sbostic 		spanp = delim;
6135297Sbostic 		do {
6235297Sbostic 			if ((sc = *spanp++) == c) {
6335297Sbostic 				if (c == 0)
6435297Sbostic 					s = NULL;
6535297Sbostic 				else
6635297Sbostic 					s[-1] = 0;
6735297Sbostic 				last = s;
6835297Sbostic 				return (tok);
6935297Sbostic 			}
7035297Sbostic 		} while (sc != 0);
7124193Skre 	}
7235297Sbostic 	/* NOTREACHED */
7324193Skre }
74