c programing strtok use

strtok is a C library function that is used to tokenize a string. It breaks a given string into a series of tokens, where each token is a substring of the original string. The function takes two arguments: the string to be tokenized and a delimiter string.

Here is a step-by-step explanation of how strtok works:

  1. The first time strtok is called, it takes the original string as the first argument and the delimiter string as the second argument.

  2. strtok searches the original string for the first occurrence of any character in the delimiter string. When it finds a delimiter character, it replaces it with a null character ('\0') and returns a pointer to the beginning of the token.

  3. The next time strtok is called, it takes NULL as the first argument. This tells strtok to continue tokenizing the original string from where it left off.

  4. strtok searches the original string for the next occurrence of any character in the delimiter string, starting from the point where it left off. Again, it replaces the delimiter character with a null character and returns a pointer to the beginning of the token.

  5. This process continues until strtok reaches the end of the original string or no more tokens can be found. In each call to strtok, it returns NULL when there are no more tokens.

It is important to note that the original string is modified by strtok. Each token is terminated by a null character, and the original string is split into separate parts.

Here is an example code snippet that demonstrates the usage of strtok:

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

int main() {
    char str[] = "This is a sample string.";
    char delimiters[] = " ";

    char *token = strtok(str, delimiters);

    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, delimiters);
    }

    return 0;
}

In this example, the original string "This is a sample string." is tokenized using the delimiter " ". Each word in the string is printed on a separate line. The output of this program would be:

This
is
a
sample
string.

This demonstrates how strtok breaks a string into tokens using a specified delimiter.