strdup() in C - Source Code Example

In this source code example, we will see how to use the strtok() function in C programming with an example.

strdup() Function Overview

The strtok() function is a standard library function in C and is used to split a string by some delimiter. The function divides the input string into sequences of tokens. Each call to strtok() returns a pointer to the next token in the string. 

One key point to remember is that strtok() actually modifies the string being split by inserting NULL bytes ('\0') where the delimiters are found.

Source Code Example

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

int main() {
    // Input string to be tokenized
    char str[] = "Hello-world_this:is;C programming";

    // Defining multiple delimiters for tokenization
    const char delimiters[] = "-_:; ";

    // Using strtok() to get the first token
    char *token = strtok(str, delimiters);

    // Extracting and printing all tokens
    while (token != NULL) {
        printf("%s\n", token);

        // Get the next token by passing NULL as the first argument
        token = strtok(NULL, delimiters);
    }

    return 0;
}

Output

Hello
world
this
is
C
programming

Explanation

1. First, the necessary headers, <stdio.h> and <string.h>, are included.

2. Inside the main function, a sample string str is defined which contains various delimiters such as hyphen, underscore, colon, semicolon, and space.

3. The delimiter characters are defined in the delimiters string.

4. The strtok() function is initially called with the str and delimiters as arguments to get the first token.

5. A while loop is then used to keep calling strtok() until all tokens are extracted. This is achieved by passing NULL as the first argument in the subsequent calls.

6. Each token is printed to the output using the printf function.

7. It's evident from the output that the string has been split based on the specified delimiters.


Comments