/*
 * Newsgroups: comp.lang.c
 * Subject: Re: Perl 'split' function in C??
 * From: scs@eskimo.com (Steve Summit)
 * Date: 21 Apr 1999 07:15:27 GMT
 *
 *  Takes a string (line) and builds an array of pointers to each word in it.
 *  Words are separated by spaces as defined by isspace().  At most maxwords
 *  pointers are calculated.  \0's are inserted in line, so that each word
 *  becomes a string in its own right.  The number of words is returned.
 */

static char RCS_ID_getwords_c[] = "$Id: getwords.c 1.5 2017-09-01 09:57:52-04 Ron Exp $";

#include <stddef.h>
#include <ctype.h>

#ifdef __cplusplus
extern "C" {
#endif

int
getwords(char *line, char *words[], int maxwords)
{
	unsigned char *p = line;
	int nwords = 0;

	if (!p) {
		return nwords;
	}

	while (1) {
		while (isspace(*p))
			p++;

		if (*p == '\0')
			return nwords;

		words[nwords++] = p;

		while (!isspace(*p) && *p != '\0')
			p++;

		if (*p == '\0')
			return nwords;

		*p++ = '\0';

		if (nwords >= maxwords)
			return nwords;
	}
}

#ifdef __cplusplus
}
#endif
