Advertisement
loulett

HW1_str

Oct 27th, 2014
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include "cstdio"
  2. #include <cstring>
  3. #include <cstdlib>
  4.  
  5. char **split(const char *str, const char *delim)
  6. {
  7.     char **res = (char**)malloc(strlen(str) * sizeof(char*));
  8.     if (!res)
  9.         return NULL;
  10.     for (int i = 0; i < (int)strlen(str); i++)
  11.     {
  12.         res[i] = NULL;
  13.     }
  14.     int n = 0, dl = strlen(delim);
  15.     const char *s = str;
  16.     const char *cd = delim;
  17.     for (; *str; ++str)
  18.     {
  19.         if (*str == *cd)
  20.         {
  21.             cd++;
  22.             if (!*cd)
  23.             {
  24.                 res[n] = (char*)malloc(str - s - dl + 2);
  25.                 memcpy(res[n], s, str - s - dl + 1);
  26.                 res[n][str - s - dl + 1] = 0;
  27.                 s = str + 1;
  28.                 cd = delim;
  29.                 n++;
  30.             }
  31.         }
  32.         else
  33.         {
  34.             cd = delim;
  35.         }
  36.     }
  37.     res[n] = (char *)malloc(str - s + 1);
  38.     strcpy(res[n], s);
  39.     return res;
  40. }
  41.  
  42. void clear(char**res)
  43. {
  44.     for (int i = 0; res[i]; i++)
  45.     {
  46.         free(res[i]);
  47.     }
  48.     free(res);
  49. }
  50.  
  51.  
  52. int main()
  53. {
  54.     char str[] = "abracadabra";
  55.     char delim[] = "br";
  56.     char **res = split(str, delim);
  57.     for (int i = 0; res[i]; i++)
  58.     {
  59.         printf("%s\n", res[i]);
  60.     }
  61.     clear(res);
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement