Skip to content

Instantly share code, notes, and snippets.

@Mroik
Created February 22, 2021 23:17
Show Gist options
  • Save Mroik/04b6089247bb84751b61834086e6cc82 to your computer and use it in GitHub Desktop.
Save Mroik/04b6089247bb84751b61834086e6cc82 to your computer and use it in GitHub Desktop.
split function for strings implemented in C
int split(char *string, char sep, int n_char, char ***array_values)
{
int n_values = 1;
int start = 0;
for(int x = 0; x < n_char; x++)
{
if(string[x] == sep)
n_values++;
}
*array_values = malloc(n_values * sizeof(char**));
for(int x = 0; x < n_values; x++)
{
for(int y = start; y <= n_char; y++)
{
if(string[y] == sep || string[y] == '\0')
{
(*array_values)[x] = malloc((y - start + 1) * sizeof(char*));
for(int z = 0; z < y - start; z++)
(*array_values)[x][z] = string[z + start];
(*array_values)[x][y - start] = '\0';
start = y + 1;
break;
}
}
}
return n_values;
}
@Mroik
Copy link
Author

Mroik commented Feb 22, 2021

char **array_of_strings;
int n_strings = split(string, ',', strlen(string), &array_of_strings);
for(int x = 0; x < n_strings; x++)
    printf("%s\n", array_of_strings[x]);

Before terminating the program memory allocated for each string will have to be deallocated, that goes for the array of pointers as well (array_of_strings).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment