This blog is under construction

Sunday, 29 April 2012

strtok example in C

Header file:
    string.h

Synopsis:
     char *strtok(char *str, char *delim);

Description:
   It parses string str for tokens delimited by any of the characters from delim and returns pointer to next token or NULL if there is no token. In subsequent calls, it parses the same string and str needs to be NULL.


strtok function C example:


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

  int main() {
        char input[100], *str;
        printf("Enter your input:");
        fgets(input, 40, stdin);
        str = strtok(input, "-");
        while (str != NULL) {
                printf("token: %s\n", str);
                // NULL is passed instead of str for subsequent calls
                str = strtok(NULL, "-");

        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input: india-is-my-country
  token: india
  token: is
  token: my
  token: country




No comments:

Post a Comment