codescracker


c

C strtok()



« Previous Chapter Next Function »


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 :

#include<string.h>
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

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
	clrscr();
	char *p;
	p = strtok("The summer soldier, the sunshine patriot", " ");
	printf(p);
	do
	{
		p = strtok('\0', ", ");
		if(p)
			printf("|%s", p);
	}while(p);
	getch();
}

« Previous Chapter Next Function »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test