str_split.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /* Adapted from http://stackoverflow.com/a/9210560 */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <assert.h>
  6. size_t split_count(char* a_str, const char a_delim) {
  7. char* tmp = a_str;
  8. char* last_comma = 0;
  9. size_t count = 0;
  10. while (*tmp) {
  11. if (a_delim == *tmp) {
  12. count++;
  13. last_comma = tmp;
  14. }
  15. tmp++;
  16. }
  17. // Add space for trailing token.
  18. count += last_comma < (a_str + strlen(a_str) - 1);
  19. // Add space for terminating null string.
  20. count++;
  21. return count;
  22. }
  23. char** str_split(char* a_str, const char a_delim) {
  24. char delim[2];
  25. delim[0] = a_delim;
  26. delim[1] = 0;
  27. size_t count = split_count(a_str, a_delim);
  28. char** result = malloc(sizeof(char*) * count);
  29. if (result) {
  30. size_t idx = 0;
  31. char* token = strtok(a_str, delim);
  32. while (token)
  33. {
  34. assert(idx < count);
  35. *(result + idx++) = strdup(token);
  36. token = strtok(0, delim);
  37. }
  38. assert(idx == count - 1);
  39. *(result + idx) = 0;
  40. }
  41. return result;
  42. }