Advertisement
rpborges97

Untitled

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