Skip to content

Instantly share code, notes, and snippets.

@cacharle
Created December 22, 2023 18:04
Show Gist options
  • Save cacharle/fe5c88acc539ed9347186f69f05ead83 to your computer and use it in GitHub Desktop.
Save cacharle/fe5c88acc539ed9347186f69f05ead83 to your computer and use it in GitHub Desktop.
Split function in C
static size_t count_segment(char const *s, char c)
{
size_t counter = 0;
int i = 0;
while (s[i])
{
if (s[i] == c)
{
i++;
continue;
}
counter++;
while (s[i] && s[i] != c)
i++;
}
return counter;
}
char **split(char const *s, char c)
{
char **strs;
size_t tab_counter;
size_t i;
size_t j;
if (s == NULL)
return (NULL);
tab_counter = count_segment(s, c);
if ((strs = (char**)malloc(sizeof(char*) * (tab_counter + 1))) == NULL)
return (NULL);
tab_counter = 0;
j = -1;
while (s[++j])
{
if (s[j] == c)
continue;
i = 0;
while (s[j + i] && s[j + i] != c)
i++;
if ((strs[tab_counter++] = strndup(&s[j], i)) == NULL)
return NULL;
j += i - 1;
}
strs[tab_counter] = NULL;
return strs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment