Skip to content

Instantly share code, notes, and snippets.

@MatheusRich
Last active June 21, 2019 15:25
Show Gist options
  • Save MatheusRich/25d270a43d9710c70930ab4c8a0acd2f to your computer and use it in GitHub Desktop.
Save MatheusRich/25d270a43d9710c70930ab4c8a0acd2f to your computer and use it in GitHub Desktop.
Function to split a string by a token and add each word to an array
#include <stdio.h>
#include <string.h>
#define MAX_NUMBER_OF_FIELDS 50
#define MAX_STRING_LENGTH 50
void split_by(char *token, char *string, char array[MAX_NUMBER_OF_FIELDS][MAX_STRING_LENGTH])
{
char *raw_string = string;
char *raw_string_info = NULL;
int i;
for (i = 0, raw_string_info = strsep(&raw_string, ","); raw_string_info != NULL; i++, raw_string_info = strsep(&raw_string, ","))
{
strcpy(array[i], raw_string_info);
}
}
int main()
{
char string[] = "my,,comma,,separated,string"; // It works with empty values
char my_array[MAX_NUMBER_OF_FIELDS][MAX_STRING_LENGTH] = {0};
split_by(token, string, my_array);
printf("------------------------\n");
int i;
for (i = 0; i < 6; i++)
{
printf("%s\n", my_array[i]);
}
printf("------------------------\n");
// Output:
// ------------------------
// my
//
// comma
//
// separated
// string
// ------------------------
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment