Search code examples
cstrtok

Strtok realization on C


I am making my own version of Strtok on C.

I almost completed, however, the last part I needed I found on the internet and I don't really understand what it does. Eventually I actually got what it does but still don't understand why it works. I am lacking of theory ;(

char* strtok_sad(char* str, const char* delim) {
    static char* next = 0;
    if (str) {
      next = str;
    }
    
    if (*next == 0) {
      return NULL;
    }

    char* c = next;
    while(strchr(delim,*c)) {
      ++c;
    }
    
    if (*c == 0) {
      return NULL;
    }
    
    char* word = c;
    while(strchr(delim,*c)==0) {
      ++c;
    }

    if (*c == 0) {
      next = c;
      return word;
    }

    *c = 0;
    next = c+1;
    return word;
}

Can somebody explain this part or at least send me an article where it is explained:

    *c = 0;
    next = c+1;

Thanks!


Solution

  • I will answer the non-offtopic version/part of the asked question.

    *c = 0; sets to 0 whatever c points to. next = c+1; makes next to point one behind c. I assume that you can spot the similarity of that rephrasing and the specification of strtok().