Created
December 22, 2023 18:04
-
-
Save cacharle/fe5c88acc539ed9347186f69f05ead83 to your computer and use it in GitHub Desktop.
Split function in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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