xref: /original-bsd/lib/libc/string/strtok.c (revision e9b82df0)
1 /*
2  * Copyright (c) 1988 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)strtok.c	5.7 (Berkeley) 06/01/90";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <stddef.h>
13 #include <string.h>
14 
15 char *
16 strtok(s, delim)
17 	register char *s, *delim;
18 {
19 	register char *spanp;
20 	register int c, sc;
21 	char *tok;
22 	static char *last;
23 
24 
25 	if (s == NULL && (s = last) == NULL)
26 		return (NULL);
27 
28 	/*
29 	 * Skip (span) leading delimiters (s += strspn(s, delim), sort of).
30 	 */
31 cont:
32 	c = *s++;
33 	for (spanp = delim; (sc = *spanp++) != 0;) {
34 		if (c == sc)
35 			goto cont;
36 	}
37 
38 	if (c == 0) {		/* no non-delimiter characters */
39 		last = NULL;
40 		return (NULL);
41 	}
42 	tok = s - 1;
43 
44 	/*
45 	 * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
46 	 * Note that delim must have one NUL; we stop if we see that, too.
47 	 */
48 	for (;;) {
49 		c = *s++;
50 		spanp = delim;
51 		do {
52 			if ((sc = *spanp++) == c) {
53 				if (c == 0)
54 					s = NULL;
55 				else
56 					s[-1] = 0;
57 				last = s;
58 				return (tok);
59 			}
60 		} while (sc != 0);
61 	}
62 	/* NOTREACHED */
63 }
64