Here is a totally new write from scratch, as that was easier to rewrite your own code (apologies if that was not your intention). A few notes:
- No need to test for previous
malloc
s. You can safelyrealloc
a NULL pointer. if (strncmp((buff + i), "\"", 1) == 0)
-- you can testbuff[i]
immediately.- Why all that
prev
shuffling? :) It's enough to loop once over your string. - I left the
temp
test for successfullyrealloc
in because you had it as well. It's actually unnecessary in my code, as it merely exitsmain
. - added: the character
"
also introduces a new 'word' when not preceded by a space.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char **tokens = NULL;
int i, count = 0, strcount;
char **temp, *iterate;
char *input = "this \"is a\" very \"very complex\" test";
iterate = input;
if (iterate)
{
while (*iterate)
{
while (*iterate == ' ')
iterate++;
if (!*iterate)
break;
temp = realloc(tokens, sizeof(char *) * (count+1));
if (temp == NULL)
{
fprintf(stderr, "Error in parsing: ran out of memory\n");
return -1;
}
tokens = temp;
if (*iterate == '\"')
{
iterate++;
strcount = 0;
while (iterate[strcount] && iterate[strcount] != '\"')
strcount++;
tokens[count] = malloc(strcount+1);
strncpy (tokens[count], iterate, strcount);
tokens[count][strcount] = 0;
count++;
iterate += strcount;
if (*iterate == '\"')
iterate++;
} else
{
strcount = 0;
while (iterate[strcount] && iterate[strcount] != ' ' && iterate[strcount] != '\"')
strcount++;
tokens[count] = malloc(strcount+1);
strncpy (tokens[count], iterate, strcount);
tokens[count][strcount] = 0;
count++;
iterate += strcount;
}
} while (*iterate);
}
for (i = 0; i < count; i++)
printf("\t%i: %s\n", i, tokens[i]);
return 0;
}
Output for this "is a" very "very complex" test
:
0: this
1: is a
2: very
3: very complex
4: test