Skip to content

Instantly share code, notes, and snippets.

@kennethlakin
Created April 24, 2013 17:07
Show Gist options
  • Save kennethlakin/5453764 to your computer and use it in GitHub Desktop.
Save kennethlakin/5453764 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *myStrtok(char * str, const char *delim)
{
static char * s = NULL;
char * ret = NULL;
if(str != NULL)
{
s = str;
}
if(s != NULL && strlen(s))
{
const size_t dlen = strlen(delim);
//Skip consecutive delimiters.
while(*s && memchr(delim, *s, dlen) != NULL)
{
++s;
}
//If the beginning of the token is not at the end of the string...
if(*s)
{
//Set our retval to the first non-delim char.
ret = s;
//Search for the next non-delim character, if any.
while(*s)
{
if(memchr(delim, *s, dlen) != NULL)
{
break;
}
else
{
++s;
}
}
if(*s)
{
//Null-terminate the token and march the stored pointer forward.
s[0] = 0;
++s;
}
}
}
return ret;
}
int main()
{
char * str = strdup(" This is a String, of Things. ! ");
const char * tok = myStrtok(str, " ,.!");
while(tok != NULL)
{
printf("'%s'\n", tok);
tok = myStrtok(NULL, " ,.!");
}
free(str);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment