Search code examples
cstrtok

what does strtok(NULL, "\n") do?


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?


Solution

  • 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"