12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <assert.h>
- size_t split_count(char* a_str, const char a_delim) {
- char* tmp = a_str;
- char* last_comma = 0;
- size_t count = 0;
- while (*tmp) {
- if (a_delim == *tmp) {
- count++;
- last_comma = tmp;
- }
- tmp++;
- }
-
- count += last_comma < (a_str + strlen(a_str) - 1);
-
- count++;
- return count;
- }
- char** str_split(char* a_str, const char a_delim) {
- char delim[2];
- delim[0] = a_delim;
- delim[1] = 0;
- size_t count = split_count(a_str, a_delim);
- char** result = malloc(sizeof(char*) * count);
- if (result) {
- size_t idx = 0;
- char* token = strtok(a_str, delim);
- while (token)
- {
- assert(idx < count);
- *(result + idx++) = strdup(token);
- token = strtok(0, delim);
- }
- assert(idx == count - 1);
- *(result + idx) = 0;
- }
- return result;
- }
|