Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Function strtok in C programming

September 18, 2013 Posted by: GPA Views: 27754 0 comments

Problem

Write simple example to split input string into a series of tokens using strtok() function in C programming.

Solution

In this section, you will know how to split string using strtok() function of header file <string.h>.

Declaration:

char *strtok( char * firstString , const char * secondString);

This function is used to split a string into a series of tokens. Token  is one piece of information example any "word".

In this example we prompt the user to enter firstString. firstString is the input text and secondString argument is delimiter (delimiter can be any character for example space or comma). In this example we use space delimiter. You can use your delimiter for example "-",":", "," and other characters.

How does it work?

Function strtok searches for the first character in the input string that is not a space. It is the first token. Then it finds the next delimiting character (spece) in the input string and replaces it with a null ('\0')  to terminate this current token. Then it saves a pointer to the next character following the token in the input string and returns a pointer to the current token.

This line "charpointer = strtok(NULL,delimiter );" in the program below continue tokenizing string. 

The NULL argument show that the call to function strtok should continue to tokenize from the location in the input string saved by the last call this function strtok. If there are no any tokens when it is called then strtok returns NULL.


Example:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>//for function strtok
//main function
int main(int argc, char *argv[])
{
char inputString[50];//variable for input String
char* delimiter=" ";//variable delimiter
char* charpointer;
printf("globalproganswer.com\n");
printf("Enter string: ");//promt user to enter some string
gets(inputString);//read string from keyboard
charpointer = strtok(inputString, delimiter); //begin tokenizing string
//show result
printf("\nResult after using function strtok is:\n");
while (charpointer != NULL ) {
printf("%s\n", charpointer );//show next word
charpointer = strtok(NULL,delimiter ); // get next token
}
printf("\n");//new line
system("PAUSE"); //delay
return 0;
}

Output

Function strtok

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe