-5

This is an example of the strtok function... I need to an explanation for this block:

while (pch != NULL)
{
    printf ("%s\n",pch);
    pch = strtok (NULL, " ");
}
return 0;

especially pch = strtok (NULL, " ");

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

int main ()
{
    char str[] ="This a sample string";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ");
    }
    return 0;
}
Evan Carslake
  • 2,267
  • 15
  • 38
  • 56
  • 6
    Have you looked up the [function documentation](http://en.cppreference.com/w/c/string/byte/strtok)? – R Sahu Mar 17 '16 at 22:13
  • 1
    Here's an [online man page for strtok](http://linux.die.net/man/3/strtok). Do you have any specific questions after reading it? – Tom Karzes Mar 17 '16 at 22:30
  • i knew that this function get tokens from a string but at this line [strtok (NULL, " "); ] i dont know where is the string which i wil get its tokens!! – Mostafa Mosaad Ibrahim Mar 17 '16 at 22:39
  • Did you actually read the man page as suggested? It tells you that info: "If str != NULL, the call is treated as the first call to strtok for this particular string....If str == NULL, the call is treated as a subsequent calls to strtok:", That is, `strtok` internally keeps state of the original string you gave it with the first call. Each subsequent `NULL` call uses that saved state. – kaylum Mar 17 '16 at 23:01
  • Your question is answered in the man page. Would it somehow help you if someone copied the entire man page, and pasted it as an answer? To be a successful programmer, you have to be willing to investigate things. If after reading about something you *still* have questions, then by all means ask them. That does not appear to be the case here. – Tom Karzes Mar 18 '16 at 00:06

1 Answers1

1

strtok() is a function from Standard C library. There're some open-source implementations of Standard C library. For example: the link below is one version from Microsoft.

http://research.microsoft.com/en-us/um/redmond/projects/invisible/src/crt/strtok.c.htm

You could see clearly in the code:

/* Skip leading delimiters if new string. */
if ( s1 == NULL ) {
   s1 = lastToken;
   if (s1 == NULL)         /* End of story? */
   return NULL;
} else
.....

The variable "lastToken" is used to track the status for strtok().

This this the reason that for the second token you should pass NULL to strtok().