I would like to have a function in C for generic string parsing. It should be able to…
- User
I would like to have a function in C for generic string parsing. It should be able to handle delimiters, string patterns, and provide a way to access the parsed tokens easily.
- Assistant
Sure, I can help you with that. Here's a C function that uses the
strtok_r()function to parse a string with delimiters and provides a way to access the parsed tokens easily. This function is thread-safe and reentrant. It also supports string patterns using thestrstr()function.c#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct { char *token; struct token_list *next; } token_list; token_list *parse_string(const char *str, const char *delimiters, const char *pattern) { token_list *head = NULL, *tail = NULL, *new_token; char *str_copy, *token, *saveptr; // Make a copy of the input string since strtok_r modifies the original string str_copy = strdup(str); if (str_copy == NULL) { fprintf(stderr, "Error: Memory allocation failed.\n"); return NULL; } // Parse the string using strtok_r token = strtok_r(str_copy, delimiters, &saveptr); while (token != NULL) { // Check if the token matches the pattern if (pattern == NULL || strstr(token, pattern) != NULL) { // Allocate memory for the new token new_token = malloc(sizeof(token_list)); if (new_token == NULL) { fprintf(stderr, "Error: Memory allocation failed.\n"); free(str_copy); return NULL; } // Copy the token and set up the linked list new_token->token = strdup(token); new_token->next = NULL; if (head == NULL) { head = new_token; tail = new_token; } else { tail->next = new_token; tail = new_token; } } // Get the next token token = strtok_r(NULL, delimiters, &saveptr); } free(str_copy); return head; } // Example usage int main() { const char *str = "This, is a test string with; multiple delimiters and a pattern: pattern"; const char *delimiters = " ,;"; const char *pattern = "pattern"; token_list *tokens = parse_string(str, delimiters, pattern); if (tokens == NULL) { fprintf(stderr, "Error: Parsing failed.\n"); return 1; } token_list *current = tokens; while (current != NULL) { printf("Token: %s\n", current->token); current = current->next; } // Free the memory allocated for the tokens current = tokens; while (current != NULL) { token_list *temp = current; current = current->next; free(temp->token); free(temp); } return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.