strparse.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "extreme.h"
  2. /******************************************************
  3. * strparse *
  4. * *
  5. * Takes a pointer to a string and a delimiter *
  6. * and a pointer to an integer to split string *
  7. * by with delimiter delimiter. *
  8. * *
  9. * Returns a pointer to a two dimensional *
  10. * array of the split parts and sets the *
  11. * integer to the number of split parts. *
  12. * *
  13. ******************************************************/
  14. char **strparse(char *string, const char *delim, int *numsecs) {
  15. char *data[MAX_SECTIONS];
  16. char **sections;
  17. char **ret;
  18. char *ptr;
  19. char *lastptr;
  20. int delimlen;
  21. int idx;
  22. int len;
  23. int delimsfound = 0;
  24. int partlen = 0;
  25. delimlen = strlen(delim);
  26. len = strlen(string);
  27. sections = data;
  28. ret = data;
  29. ptr = string;
  30. for (idx = 0; idx < len; idx++) {
  31. if (delimsfound > MAX_SECTIONS)
  32. return ret;
  33. if (strncmp(string + idx, delim, delimlen) == 0) {
  34. if (delimsfound == 0) {
  35. lastptr = string;
  36. } else {
  37. partlen -= delimlen;
  38. lastptr = ptr - partlen;
  39. }
  40. if (partlen == 0)
  41. *sections = NULL;
  42. else {
  43. if ((*sections = malloc(partlen)) == NULL) {
  44. errno = ENOMEM;
  45. return NULL;
  46. }
  47. strncpy(*sections, lastptr, partlen);
  48. }
  49. partlen = 0;
  50. delimsfound++;
  51. sections++;
  52. }
  53. partlen++;
  54. ptr++;
  55. }
  56. if (idx == len) {
  57. if (partlen == 0)
  58. *sections = NULL;
  59. else {
  60. if ((*sections = malloc(partlen)) == NULL) {
  61. errno = ENOMEM;
  62. return NULL;
  63. }
  64. partlen -= delimlen;
  65. strncpy(*sections, ptr - partlen, partlen);
  66. }
  67. }
  68. *numsecs = delimsfound + 1;
  69. if ((*data = realloc(*data, *numsecs * sizeof(char *))) == NULL) {
  70. errno = ENOMEM;
  71. return NULL;
  72. }
  73. return ret;
  74. }