top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How strtok library function is implemented ?

+2 votes
884 views
How strtok library function is implemented ?
posted Jun 13, 2015 by Harshita

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

its a c library function which is used to tokenize a given string based on the token character provided.
its prototype is char *strtok(char *str, const char*tok).

char a[] = "This is-queryhome.com-QA-website";
char *tok = strtok(a, '-');
while(tok!=NULL)
{
     printf("%s\n" tok);
     tok = strtok(NULL, '-');
}

Output:

This is
queryhome.com
QA
website

Basically strtok() function maintains a local static reference, which points to the next token in the string, when we pass a null to strtok() its uses that internal reference. This is the reason strtok is neither re-entrant nor thread safe. as you pass the new reference to strtok() that old internal reference gets overwrite.

answer Jun 13, 2015 by Prakash Singh
+1 vote

This is my implementation, does not require any explanation -

#include <stdio.h>
#include <string.h>  
#include <malloc.h>

char* my_strtok(char* s, char* delm)
{
    static int currIndex = 0;
    char *W = (char *)malloc(sizeof(char)*100);
    int i = currIndex, k = 0, j = 0;

    if(!s || !delm || s[currIndex] == '\0')
      return NULL;

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

It:
    W[i] = 0;
    currIndex = i+1;
    return W;
}

int main(void)
{
  char s[100] = "I am JameBond 007";
  char delm[] = " ";
  char *str = my_strtok(s, delm);
  while(str){
    printf("%s\n", str);
    free(str);
    str = my_strtok(s, delm);
  }
  return 0;
}
answer Jun 13, 2015 by Pardeep Kohli
Similar Questions
+1 vote

I want to build my own library in C, can someone help me with this?

0 votes

While reading shared library and PLT (Procedure Linkage Table) I came under a term Trampolines arrangement.

can any one share some info on it ?

+1 vote

I am looking for the strtok functionality to be implemented in C. Please help me...

+1 vote

Are there any defined rules that should be considered while writing function definition ?

...