C strtok()

The strtok() function returns a pointer to the next token in the string pointed to by str1. The characters making up the string pointed to by str2 are the delimiters that determine the token. A null pointer is returned when there is no token to return.

To tokenize a string, the first call to strtok() must have str1 point to the string being tokenized. Subsequent calls must use a null pointer for str1. In this way the entire string can be reduced to its tokens.

It is possible to use a different set of delimiters for each call to strtok().

strtok() Syntax

Following is the syntax of the strtok() function :

char *strtok(char *str1, const char *str2);

strtok() Example

Following program tokenizes the string "The summer soldier, the sunshine patriot," with spaces and commas being the delimiters. The output is
The | summer | soldier | the | sunshine | patriot

void main()
	char *p;
	p = strtok("The summer soldier, the sunshine patriot", " ");
		p = strtok('\0', ", ");
			printf("|%s", p);

C Online Test

« Previous Chapter Next Function »

Like/Share Us on Facebook 😋