[net.sources] strtok

jmg@dolphy.UUCP (Intergalactic Psychic Police Of Uranus) (10/16/85)

*** RE: a program that stands up for America ***

It seems that the evil empire has struck again: there is no
strtok(3) in ucb UNIX, or 4.2 at least...and that means that
those of you who received typo(1), a program to prevent
typing errors caused by the red scourge, were left defenseless.

So, I've oil't down my body, built up my pecks, plugged a few
slant-eye commie automatons, donned the clothes of a middle-america
down home television minister and implemented strtok(3) according
to the specs of at&t 5.2 manual.  Here is its, caveats and all:


/* strtok(3) (from the manual system 5.2):
 * char *strtok(s1,s2)
 * char *s1, *s2;
 *  strtok considers the string s1 to consist of a sequence
 * of zero or more text tokens separated by spans of one or more
 * characters from the separator string s2.  The first call (with
 * pointer s1 specified) returns a pointer to the first character of
 * the first token, and will have written a null character into s1
 * immediatlely following the returned token.  The function keeps
 * track of its position in the string between separate calls, so
 * that subsequent calls (which must be made with the first arguemtn
 * a NULL pointer) will work through the string s1 immediately
 * following that token.  In this way subsequent calls will work
 * through the string s1 until no tokens remain.  The separator
 * string s2 may be different from call to call.  When no token
 * remains in s1, a NULL pointer is returned.
 *
 * Below is my simulation of at&t unix 5.2 strtok(3) function for use
 * with the typo(1) program for ucb unix 4.2... I tried to make
 * it do what the description above says, but I didn't try very
 * hard...just enough for it to work with typo(1), which I
 * submitted a few days ago.  That is, it may be correct...but, I
 * haven't rigorously tested it... If it's adequate in general, tell me!
 * 
 * Jeffrey Greenberg ihnp4!allegra!phri!dolphy!jmg
 * Tue Oct 15 17:25:23 EDT 1985
 */

#include <stdio.h>

char *
strtok( source, separators )
char *source, *separators;
{
	static char *ch;
	register char *sep, *token;

	/* if no source supplied, use the previous one.
	 */
	if( source != (char *) NULL )
		ch = source;

	/* For each character in the source string, see if it is a separator
	 * character.
	 */
	for( token = ch; *ch; ++ch ) {
		for( sep = separators; *sep; ++sep ) {

			/* look for a separator
			 */
			if( *ch == *sep ) {
				/* Got one, put a null there and move the
				 * saved source pointer up one for next time.
				 */
				*ch = 0;
				++ch;
				return token;
				break;
			}
		}
	}

	/* If nothing was found, then return nothing
	 * else return the token
	 */
	if( token == ch )
		return (char *) NULL;
	else
		return token;
}