Advertisement
codemonkey

Untitled

Oct 11th, 2011
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. char** strsplit(char* const str, char const delimiter)
  2. {
  3.     int inputlen = strlen(str),
  4.         i,
  5.         currwordlen = 20, // To keep track of the current word max length
  6.         wordlen = 0, // To keep track of the current word actual length
  7.         wordnum = 0, // To keep track of the current number of words
  8.         inword = 0; // To separate words
  9.  
  10.     // Input validation
  11.     if(inputlen > STRSPLIT_MAX_INPUT_LENGTH)
  12.     {
  13.         errno = STRSPLIT_ERROR_INPUT_TOO_LONG;
  14.         return NULL;
  15.     }
  16.  
  17.     // Allocate the output variable. Assume one word with 20 letters to begin
  18.     // with.
  19.     char** output = NULL;
  20.  
  21.     // Loop through the input string and separate words
  22.     for(i = 0; i < inputlen; i++)
  23.     {
  24.         // If this character is not whitespace, we're in a word
  25.         if(!isspace(i))
  26.         {
  27.             // We're now in a word
  28.             if(!inword)
  29.             {
  30.                 inword = 1;
  31.                 wordnum++;
  32.                 wordlen++;
  33.  
  34.                 // Reallocate output to the number of current words. If NULL is
  35.                 // passed as the first argument realloc will behave as malloc.
  36.                 output = realloc(output, sizeof(char*) * wordnum);
  37.  
  38.                 // Allocate room for 20 characters for this new word
  39.                 *(output + (wordnum - 1)) = malloc(sizeof(char) * 20);
  40.  
  41.                 // Put this character into the freshly allocated space
  42.                 **(output + (wordnum - 1)) = *(str + i);
  43.             }
  44.             // Continue word
  45.             else
  46.             {
  47.                
  48.             }
  49.         }
  50.         else
  51.         {
  52.             inword = 0;
  53.         }
  54.     };
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement