caps_lock caps_lock - 3 months ago 82
C Question

Implementation of strtok() function

I need to write my function strtok. Below is my code. The problem is - I can't display result string. In code I use strcpy() and then display new array.
Is it possible to display string using just pointer *str?



#include <stdio.h>
#include <string.h>
char* my_strtok(char* s, char* delm){
char W[100];
int i = 0, k = 0, j = 0;
char *ptr;
static char *Iterator;
ptr = s;

if (s == NULL){
s = Iterator;
}
while (s[i] != '\0'){
j = 0;
while (delm[j] != '\0'){
if (s[i] != delm[j])
W[k] = s[i];
else goto It;
j++;
}
ptr++;
i++;
k++;
}
It:
W[i] = 0;
Iterator = ++ptr;
return W;
}

int main(void){
char s[100];
char delm[] = " ";
gets(s);
char newstr[100];
char *str = my_strtok(s, delm);
strcpy(newstr, str);
for(int i = 0; newstr[i] != '\0'; i++)
printf("%c", newstr[i]);
return 0;
}



Answer

Internal implementation of strtok has already been discussed here:

How does strtok() split the string into tokens in C?

In your type of implementation ( calling it your type because it is quite different from the actual one), you have not allocated any memory dynamically to the local variable 'W'. So when you return it, it is not guaranteed that you will receive the string correctly because that memory which was locally allocated to 'W' is not reserved for it anymore in the calling function. Apart from this, there are many unnecessary variables used in the code. And also, it needs proper re-structuring. For your better understanding I have modified your code(keeping it in your style as far as possible) to do the required job:

#include <stdio.h>
#include <string.h>  
#include <malloc.h>
char* my_strtok(char* s, char* delm)
{
    static int currIndex = 0;
    if(!s || !delm || s[currIndex] == '\0')
    return NULL;
    char *W = (char *)malloc(sizeof(char)*100);
    int i = currIndex, k = 0, j = 0;
    //char *ptr;
    //static char *Iterator = s;
    //ptr = s;

    /*if (s == NULL){
    s = Iterator;
    }*/
    while (s[i] != '\0'){
        j = 0;
        while (delm[j] != '\0'){
            if (s[i] != delm[j])
                W[k] = s[i];
            else goto It;
            j++;
        }
        //ptr++;
        i++;
        k++;
    }
It:
    W[i] = 0;
    currIndex = i+1;
    //Iterator = ++ptr;
    return W;
}

int main(void)
{
char s[100] = "my name is khan";
char delm[] = " ";
//char newstr[100];
char *str = my_strtok(s, delm);
while(str){
    printf("%s", str);
    free(str);
    str = my_strtok(s, delm);
}
//strcpy(newstr, str);
//for(int i = 0; newstr[i] != '\0'; i++)
//    printf("%c", newstr[i]);
return 0;
}