Jump to content

I dont understand this parser code

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Salrandin

Salrandin

    Newbie

  • Members
  • PipPip
  • 10 posts
[HIGHLIGHT="C"]void my_split(const char* tosplit, const char* delim, char** parsed, int* len)
{
char *local = strdup(tosplit);
char *tok = strtok(local, delim);
int i = 0;
while(tok) {
*parsed++ = strdup(tok);
i++;
tok = strtok(NULL, delim);
}
*len = i;
free(local);
}[/HIGHLIGHT]

Can anyone explain this to me? i know it parses with a delimeter
but im not quite sure how it works

#2
limo

limo

    Newbie

  • Members
  • PipPip
  • 14 posts
Here you go, comments added :cool:


  char *local = strdup(tosplit); // makes a copy of tosplit, and 

  // returns a pointer to the allocated copy


    char *tok = strtok(local, delim); // split local into tokens using

    // delim, store the first token in tok


    int i = 0; // counter for token


    while(tok) { // while token is not null


        *parsed++ = strdup(tok); // makes a copy of token, 

        // returns a pointer to the allocated copy which is stored in 

        // parsed, parsed is then increment to point to the next 

        // pointer


        i++; // increment the number of tokens parsed


        tok = strtok(NULL, delim); // get next token


    }


    *len = i; // stores the number of tokens in len


    free(local); // frees the memory taken up local


// when the function returns, *parsed will contain tokens created from tosplit


#3
Salrandin

Salrandin

    Newbie

  • Members
  • PipPip
  • 10 posts
thx, it takes in a string as a delimiter right?
On C/C++ I use MS Visual Studios 2005 Express (yuck)
On Java I use BlueJ (Rocks!)

#4
limo

limo

    Newbie

  • Members
  • PipPip
  • 14 posts
NP. Yes the function takes in both the string to tokenise, and a string which contains the delimiters.