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?
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.
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With