[ create a new paste ] login | about

Link: http://codepad.org/2lBkZk0w    [ raw code | output | fork ]

C, pasted on Feb 11:
#include <string.h>
#include <stdio.h>

char* my_strtok_r(char* str, const char* delim, char** saveptr)
{
    char* end;

    /* if `str` is `NULL`, we operate on previously-saved position */
    if(!str) str = *saveptr;
    /* we've dealt with the last token */
    if(!*str) return NULL;

    /* find next token */
    end = str + strcspn(str, delim);
    /* `*saveptr` stores where we'll continue in the next iteration */
    *saveptr = end + strspn(end, delim);
    /* zero-terminate our token */
    *end = 0;
    return str;
}

int main(void)
{
    char str[] = "hello, world! abc, def.";

    char* save;
    char* ret = my_strtok_r(str, " ,.!", &save);
    while(ret)
    {
        printf("%s\n", ret);
        ret = my_strtok_r(NULL, " ,.!", &save);
    }
    return 0;
}


Output:
1
2
3
4
hello
world
abc
def


Create a new paste based on this one


Comments: