xref: /csrg-svn/lib/libc/string/strtok.c (revision 42637)
124193Skre /*
235297Sbostic  * Copyright (c) 1988 Regents of the University of California.
334479Sbostic  * All rights reserved.
434479Sbostic  *
5*42637Sbostic  * %sccs.include.redist.c%
624193Skre  */
724193Skre 
826538Sdonn #if defined(LIBC_SCCS) && !defined(lint)
9*42637Sbostic static char sccsid[] = "@(#)strtok.c	5.7 (Berkeley) 06/01/90";
1034479Sbostic #endif /* LIBC_SCCS and not lint */
1124193Skre 
1242181Sbostic #include <stddef.h>
1342181Sbostic #include <string.h>
1435297Sbostic 
1524193Skre char *
1635297Sbostic strtok(s, delim)
1735297Sbostic 	register char *s, *delim;
1824193Skre {
1935297Sbostic 	register char *spanp;
2035297Sbostic 	register int c, sc;
2135297Sbostic 	char *tok;
2235297Sbostic 	static char *last;
2324193Skre 
2424193Skre 
2535297Sbostic 	if (s == NULL && (s = last) == NULL)
2635297Sbostic 		return (NULL);
2735297Sbostic 
2835297Sbostic 	/*
2935297Sbostic 	 * Skip (span) leading delimiters (s += strspn(s, delim), sort of).
3035297Sbostic 	 */
3135297Sbostic cont:
3235297Sbostic 	c = *s++;
3335297Sbostic 	for (spanp = delim; (sc = *spanp++) != 0;) {
3435297Sbostic 		if (c == sc)
3535297Sbostic 			goto cont;
3624193Skre 	}
3724193Skre 
3835297Sbostic 	if (c == 0) {		/* no non-delimiter characters */
3935297Sbostic 		last = NULL;
4035297Sbostic 		return (NULL);
4124193Skre 	}
4235297Sbostic 	tok = s - 1;
4324193Skre 
4435297Sbostic 	/*
4535297Sbostic 	 * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
4635297Sbostic 	 * Note that delim must have one NUL; we stop if we see that, too.
4735297Sbostic 	 */
4835297Sbostic 	for (;;) {
4935297Sbostic 		c = *s++;
5035297Sbostic 		spanp = delim;
5135297Sbostic 		do {
5235297Sbostic 			if ((sc = *spanp++) == c) {
5335297Sbostic 				if (c == 0)
5435297Sbostic 					s = NULL;
5535297Sbostic 				else
5635297Sbostic 					s[-1] = 0;
5735297Sbostic 				last = s;
5835297Sbostic 				return (tok);
5935297Sbostic 			}
6035297Sbostic 		} while (sc != 0);
6124193Skre 	}
6235297Sbostic 	/* NOTREACHED */
6324193Skre }
64