Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2014
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <assert.h>
  5.  
  6. char** str_split(char* a_str, const char a_delim)
  7. {
  8. char** result = 0;
  9. size_t count = 0;
  10. char* tmp = a_str;
  11. char* last_comma = 0;
  12. char delim[2];
  13. delim[0] = a_delim;
  14. delim[1] = 0;
  15.  
  16. /* Count how many elements will be extracted. */
  17. while (*tmp)
  18. {
  19. if (a_delim == *tmp)
  20. {
  21. count++;
  22. last_comma = tmp;
  23. }
  24. tmp++;
  25. }
  26.  
  27. /* Add space for trailing token. */
  28. count += last_comma < (a_str + strlen(a_str) - 1);
  29.  
  30. /* Add space for terminating null string so caller
  31. knows where the list of returned strings ends. */
  32. count++;
  33.  
  34. result = malloc(sizeof(char*) * count);
  35.  
  36. if (result)
  37. {
  38. size_t idx = 0;
  39. char* token = strtok(a_str, delim);
  40.  
  41. while (token)
  42. {
  43. assert(idx < count);
  44. *(result + idx++) = strdup(token);
  45. token = strtok(0, delim);
  46. }
  47. assert(idx == count - 1);
  48. *(result + idx) = 0;
  49. }
  50.  
  51. return result;
  52. }
  53.  
  54. int main()
  55. {
  56. char months[] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
  57. char** tokens;
  58.  
  59. printf("months=[%s]nn", months);
  60.  
  61. tokens = str_split(months, ',');
  62.  
  63. if (tokens)
  64. {
  65. int i;
  66. for (i = 0; *(tokens + i); i++)
  67. {
  68. printf("month=[%s]n", *(tokens + i));
  69. free(*(tokens + i));
  70. }
  71. printf("n");
  72. free(tokens);
  73. }
  74.  
  75. return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement