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,
- currwordlen = 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
- // 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 whitespace, we're in a word
- if(!isspace(i))
- {
- // We're now in a word
- if(!inword)
- {
- inword = 1;
- wordnum++;
- wordlen++;
- // Reallocate output to the number of current words. If NULL is
- // passed as the first argument realloc will behave as malloc.
- output = realloc(output, sizeof(char*) * wordnum);
- // Allocate room for 20 characters for this new word
- *(output + (wordnum - 1)) = malloc(sizeof(char) * 20);
- // Put this character into the freshly allocated space
- **(output + (wordnum - 1)) = *(str + i);
- }
- // Continue word
- else
- {
- }
- }
- else
- {
- inword = 0;
- }
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement