Home > Electronics Tutorials > C Language Tutorial > string.h - strtok

C Language Programming Library Reference Guide

string.h - strtok

Declaration: char *strtok(char *str1, const char *str2); Breaks string str1 into a series of tokens. If str1 and str2 are not null, then the following search sequence begins. The first character in str1 that does not occur in str2 is found. If str1 consists entirely of characters specified in str2, then no tokens exist and a null pointer is returned. If this character is found, then this marks the beginning of the first token. It then begins searching for the next character after that which is contained in str2. If this character is not found, then the current token extends to the end of str1. If the character is found, then it is overwritten by a null character, which terminates the current token. The function then saves the following position internally and returns.

Subsequent calls with a null pointer for str1 will cause the previous position saved to be restored and begins searching from that point. Subsequent calls may use a different value for str2 each time.

Returns a pointer to the first token in str1. If no token is found then a null pointer is returned.

Example:

#include<string.h>
#include<stdio.h>

int main(void)
{
  char search_string[]="Woody Norm Cliff";
  char *array[50];
  int loop;

  array[0]=strtok(search_string," ");
  if(array[0]==NULL)
   {
    printf("No test to search.\n");
    exit(0);
   }

  for(loop=1;loop<50;loop++)
   {
    array[loop]=strtok(NULL," ");
    if(array[loop]==NULL)
      break;
   }

  for(loop=0;loop<50;loop++)
   {
    if(array[loop]==NULL)
      break;
    printf("Item #%d is %s.\n",loop,array[loop]);
   }

  return 0;
}
This program replaces each space into a null character and stores a pointer to each substring into the array. It then prints out each item.
Note: To report broken links or to submit your projects, tutorials please email to Webmaster

Discover

     more......