-2

The C library function char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim.

What happens when you put s = strtok(NULL, "\n")? what does it mean splitting null by \n?

needChelp1
  • 19
  • 1
  • 2
  • 8
    Tried [`man strtok`](https://linux.die.net/man/3/strtok)? – Eugene Sh. Jul 06 '18 at 14:06
  • 3
    Or [cppreference.com/.../strtok](https://en.cppreference.com/w/cpp/string/byte/strtok)? – HolyBlackCat Jul 06 '18 at 14:08
  • "In subsequent calls, str should be NULL, and saveptr should be unchanged since the previous call". Maybe you look at "subsequent call" - see lines above for other `strtok`. – i486 Jul 06 '18 at 14:08
  • 2
    I'm voting to close this question as off-topic because this is a basic question that can be answered by reading any basic C book/tutorial. – haccks Jul 06 '18 at 14:17

1 Answers1

2

It doesn't mean splitting NULL by \n.

If you pass a non-NULL value, you are asking it to start tokenizing the passed string.

If you pass a NULL value, you are asking to continue tokenizing the same string as before (usually used in loops).

Example:

int main(void)
{
   char *token, string[] = "a string, of,; ;;;,tokens";

   token = strtok(string, ", ;");
   do
   {
      printf("token: \"%s\"\n", token);
   }
   while (token = strtok(NULL, ", ;"));
}

Result:

token: "a"                                                                                                                                                   
token: "string"                                                                                                                                              
token: "of"                                                                                                                                                  
token: "tokens"     
Vlad C
  • 447
  • 2
  • 6
  • 17
  • If no such token exists, `token = strtok(string, ", ;")` will return `NULL` and `printf("token: \"%s\"\n", token);` will attempt to print a `NULL` character. – Hatefiend Feb 25 '19 at 22:47