how is strtok written?

Posted on 2005-04-30
Last Modified: 2010-04-02

I am trying to write the code as to how strtok is written (u know, something like an implementation of strcpy etc)... I am okay with what happens on the first call... something like this maybe:

char *strtok(const char *s1, char *delim)
    char *retStr;
    int i=0;

    while(s1[i]  != *delim) {i++;}

    retStr = (char *)malloc(i*sizeof(char));
    return strncpy(retStr, s1, i);

I am not so strong with pointers and therefore please correct me if I am wrong in the function. But what next? when I pass NULL on my second call, how does the function know my previous string? how does it send the second token?

Question by:srinivas_vemla
    LVL 45

    Accepted Solution

    Hi srinivas_vemla,

    You're going to need a static pointer variable to keep track of the "current" position.  This becomes the variable that you'll increment as you advance through the string.

    Then, when you enter your routine:

      if (s1!=NULL)
        TheStaticPointer = s1;

    That should just about do it.

    Good Luck!
    LVL 55

    Assisted Solution

    by:Jaime Olivares

    Author Comment

    Thanks guys,

    The suggestion and the links were very helpful...

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Suggested Solutions

    Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode ( They will have you believe that Unicode requires you to use…
    This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
    The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
    The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now