Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use NULL in strtok()?

Tags:

c

null

strtok

Why do we use NULL in strok() function?

while (h != NULL)
{
    h = strtok(NULL, delim);  
    if (hold != NULL) 
      printf("%s", hold);    
}

What does this program do when *h is pointing to a string?

like image 713
user3600999 Avatar asked May 04 '14 12:05

user3600999


People also ask

Does strtok add NULL?

strtok() returns a NULL pointer. The token ends with the first character contained in the string pointed to by string2. If such a character is not found, the token ends at the terminating NULL character.

What does strtok () do in C?

The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.

Can strtok return empty string?

This function returns an empty string when no more tokens are found. Each call modifies sTokenString by substituting a null character for each delimiter that is encountered. Defines the string to search in. Each call modifies this parameter by substituting a null character for each delimiter that is encountered.

What does strtok return if no delimiter?

The first call in the sequence searches s for the first character that isn't contained in the current delimiter string sep. If no such character is found, then there are no tokens in s, and strtok() returns a NULL pointer.


1 Answers

strtok is part of the C library and what it does is splitting a C null-delimited string into tokens separated by any delimiter you specify.

The first call to strtok must pass the C string to tokenize, and subsequent calls must specify NULL as the first argument, which tells the function to continue tokenizing the string you passed in first.

The return value of the function returns a C string that is the current token retrieved. So first call --> first token, second call (with NULL specified) --> second token, and so on.

When there are no tokens left to retrieve, strtok returns NULL, meaning that the string has been fully tokenized.

Here's the reference, with an example: http://www.cplusplus.com/reference/cstring/strtok/

like image 164
Banex Avatar answered Sep 23 '22 13:09

Banex