Need strtok source!

Lynn Lively Lynn.Lively at p4694.f506.n106.z1.fidonet.org
Sat Jan 20 06:28:48 AEST 1990


In an article of <16 Jan 90 22:40:10 GMT>, ssdken at jarthur.Claremont.EDU (Ken Nelson) writes:

 KN>From: ssdken at jarthur.Claremont.EDU (Ken Nelson)
 KN>Date: 16 Jan 90 22:40:10 GMT
 KN>Organization: Harvey Mudd College, Claremont, CA
 KN>Message-ID: <3796 at jarthur.Claremont.EDU>
 KN>Newsgroups: comp.lang.c
 KN>
 KN>Hello,
 KN>
 KN>  I need source code for the ansi function 'strtok'.  We are porting
 KN>  from a system that has it, to one that doesn't.
 KN>
 KN>
 KN>                        Thanks for any help.
 KN>
 KN>
 KN>                        Ken Nelson
 KN>                        Principal Engineer
 KN>                        Software Systems Design
 KN>                        3627 Padua Avenue
 KN>                        Claremont, CA 91711
 KN>                        (714) 624-2402

 Ken,
     Here is a function that should be able to stand in for strtok()
took me about half an hour to write. I'm including a test program too.
It seems to work as expected, but you may want to check it out a bit more
before you trust it in production.
 Your Servant,
      Lynn

-------------------------------------------------------------------------

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

char * mytok (char * object, char * delims);

void main ()
  {
    char s[256];
    char delims[256];
    char * wk_ptr;
    while (1)
      {
        printf ("Enter String to search:\n");
        gets (s);
        printf ("Enter Delimeters to search for:\n");
        gets (delims);

        wk_ptr = s;
        while ((wk_ptr = mytok (wk_ptr, delims)) != NULL)
          {
            printf ("String found: '%s'\n", wk_ptr);
            wk_ptr = NULL;
          }
      }
  }

/*
 * Works like strtok()
 */

char * mytok (char * object, char * delims)
  {
    static char * obj_ptr = NULL;
    static char * end_ptr = NULL;

    char * wk_ptr;
    char * min_ptr;

    if (object != NULL)
      {
        obj_ptr = object;
        end_ptr = object + strlen (object);
      }

    if (obj_ptr == end_ptr)
      {
        return (NULL);
      }

    min_ptr = end_ptr;
    while (*delims != '\0')
      {
        wk_ptr = strchr (obj_ptr, *delims++);
        if (wk_ptr != NULL)
          {
            min_ptr = (wk_ptr < min_ptr) ? wk_ptr : min_ptr;
          }
      }

    if (min_ptr != end_ptr)
      {
        wk_ptr   = obj_ptr;
        obj_ptr = min_ptr + 1;
        while (obj_ptr < end_ptr)
          {
            if (*obj_ptr == *min_ptr)
              {
                *obj_ptr++ = '\0';
              }
            else
              {
                break;
              }
          }

        *min_ptr = '\0';
      }
    else
      {
        wk_ptr   = obj_ptr;
        obj_ptr = end_ptr;
      }

    return (wk_ptr);
  }



More information about the Comp.lang.c mailing list