SHARE
TWEET

Split Function C

Waseemrkab Oct 14th, 2019 (edited) 136 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef char* string;
  6.  
  7. char ignoreCase(char let)
  8. {
  9.     return (let >= 'A' && let <= 'Z') ? ('a' + let - 'A') : let;
  10. }
  11.  
  12. string* split(const string str, const char let, int* size)
  13. {
  14.     if (str == NULL)
  15.         return NULL;
  16.     string* splited = NULL;
  17.     string ptr = str;
  18.     char buffer[100], prev = ' ';
  19.     int i;
  20.     while (*ptr)
  21.     {
  22.         if (ignoreCase(*ptr) == ignoreCase(let) && prev == ' ')
  23.         {
  24.             i = 0;
  25.             splited = realloc(splited, sizeof(string) * (*size + 1));
  26.             while (*ptr && *ptr != ' ')
  27.             {
  28.                 buffer[i++] = *ptr;
  29.                 *ptr++;
  30.             }
  31.             buffer[i] = '\0';
  32.             splited[*size] = malloc(sizeof(char) * (strlen(buffer) + 1));
  33.             strcpy(splited[(*size)++], buffer);
  34.         }
  35.         prev = *ptr++;
  36.     }
  37.     return splited;
  38. }
  39.  
  40. int main()
  41. {
  42.     string str = "world    hello this      hhhiiiiii wooo  hooomannnn Rony Goodman got a good mark  hask";
  43.     char letter = 'h';
  44.     int sizeofArray = 0;
  45.     string* strings = split(str, letter, &sizeofArray);
  46.     for (int i = 0; i < sizeofArray; ++i)
  47.         printf("%s\n", strings[i]);
  48.     for (int i = 0; i < sizeofArray; ++i)
  49.         free(strings[i]);
  50.     free(strings);
  51.     return 0;
  52. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top