Strsep() function in C
×


Strsep() function in C

64

The strsep function in C is a powerful tool for parsing and tokenizing strings.

It allows developers to split strings into smaller tokens based on a specified delimiter, facilitating various string manipulation tasks.

Syntax strsep function in C:

The syntax of the strsep function is as follows:

char *strsep(char **string_ptr, const char *delim); 

Parameters:

string_ptr: A pointer to a pointer to the input string.

Upon completion, this pointer will be updated to point to the remainder of the input string beyond the token found.

delim: A pointer to a null-terminated string containing delimiter characters.

The strsep function searches for any of these characters to determine token boundaries.

Return Value:

The strsep function returns a pointer to the next token found in the input string.

If no token is found, it returns NULL.

Example:

// Program for strsep in C

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

int main() {
    char str[] = "apple, orange, banana, grape";
    char *token;
    char *rest = str; // Pointer to the current position in the string
    
    printf("Original string: %s\n", str);
    
    while ((token = strsep(&rest, ",")) != NULL) {
        printf("Token: %s\n", token);
    }
    
    return 0;
}

Output:

Original string: apple,orange,banana,grape
Token: apple
Token: orange
Token: banana
Token: grape

In this example program:

We include the necessary header files <stdio.h> and <string.h>.

We declare a character array str containing the string "apple, orange, banana, grape".

We declare a pointer token to store the current token extracted from the string.

We initialize a pointer rest to point to the beginning of the input string.

Inside the while loop, we repeatedly call strsep(&rest, ",") to extract tokens from the string.

The strsep function modifies the rest pointer to point to the remainder of the string after the token.

If a token is found, it is printed to the console.

The loop continues until there are no more tokens in the string.

This program demonstrates how the strsep function can be used to tokenize a string based on a delimiter, allowing developers to process string data efficiently.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments