Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- char** strsplit(char* const str, char const delimiter)
- {
- int inputlen = strlen(str),
- i,
- wordmaxlen = 20, // To keep track of the current word max length
- wordlen = 0, // To keep track of the current word actual length
- wordnum = 0, // To keep track of the current number of words
- inword = 0, // To separate words
- wordfinished = 0; // To deal with cases where the delimiter is the last
- // character in the string
- // Input validation
- if(inputlen > STRSPLIT_MAX_INPUT_LENGTH)
- {
- errno = STRSPLIT_ERROR_INPUT_TOO_LONG;
- return NULL;
- }
- // Allocate the output variable. Assume one word with 20 letters to begin
- // with.
- char** output = NULL;
- // Loop through the input string and separate words
- for(i = 0; i < inputlen; i++)
- {
- // If this character is not the delimiter, we're in a word
- if(*(str + i) != delimiter)
- {
- // We're now in a word
- if(!inword)
- {
- puts("STARTING NEW WORD");
- inword = 1; // Mark that we're now in a word
- wordmaxlen = 20; // Set or reset the word max length
- wordnum++; // Increase number of words by 1
- wordlen = 1; // Set the length of this word to 1
- wordfinished = 0; // Set this word to not finished
- // Reallocate output to the number of current words. If NULL is
- // passed as the first argument realloc will behave as malloc.
- // Remember to make room for a nullbyte
- output = realloc(output, sizeof(char*) * (wordnum + 1));
- // Allocate room for 20 characters for this new word
- *(output + (wordnum - 1)) = malloc(sizeof(char) * wordmaxlen);
- // Put this character into the freshly allocated space
- **(output + (wordnum - 1)) = *(str + i);
- }
- // Continue word
- else
- {
- // The word is now 1 character longer
- wordlen++;
- // If we've breached the max length of the word, reallocate ten
- // more characters. Also remember to compensate for the
- // required nullbyte
- if(wordlen > (wordmaxlen - 1))
- *(output + (wordnum - 1)) =
- realloc(*(output + (wordnum - 1)), (wordmaxlen += 10));
- // Put the current character into the current char spot in the
- // current word
- *(*(output + (wordnum - 1)) + (wordlen - 1)) = *(str + i);
- }
- }
- // Delimiter has been hit! Wrap up the previous word if there is one
- else
- {
- // If we were in a word, end that word here. Otherwise, ignore
- if(inword)
- {
- puts("ENDING WORD");
- // No longer in a word
- inword = 0;
- // The nullbyte
- *(*(output + (wordnum - 1)) + (wordlen)) = '\0';
- // Mark this word as finished
- wordfinished = 1;
- }
- }
- }
- // If the loop finished in the middle of a word, finish that word now
- if(!wordfinished)
- {
- puts("ENDING WORD");
- *(*(output + (wordnum - 1)) + (wordlen)) = '\0';
- }
- *(output + wordnum) = NULL;
- printf("WORD NUMBER %d\n", wordnum);
- return output;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement