diff --git a/photon/libc/include/string.h b/photon/libc/include/string.h index 2b1e6cb..5d7822e 100644 --- a/photon/libc/include/string.h +++ b/photon/libc/include/string.h @@ -23,6 +23,9 @@ extern char *strrchr(const char *s, int c); extern char *strdup(const char *s); +extern char *strtok(char *s, const char *delim); +extern char *strtok_r(char *s, const char *delim, char **sp); + #if defined(__cplusplus) } /* extern "C" */ #endif diff --git a/photon/libc/string/strtok.c b/photon/libc/string/strtok.c new file mode 100644 index 0000000..7130fd6 --- /dev/null +++ b/photon/libc/string/strtok.c @@ -0,0 +1,62 @@ +#include + +static char *global_sp = NULL; + +char *strtok(char *str, const char *delim) +{ + return strtok_r(str, delim, &global_sp); +} + +char *strtok_r(char *str, const char *delim, char **sp) +{ + int i = 0; + int len = strlen(delim); + + if (len == 0) { + return NULL; + } + + if (!str && !sp) { + return NULL; + } + + if (str) { + *sp = str; + } + + char *p_start = *sp; + while (1) { + for (i = 0; i < len; i++) { + if (*p_start == delim[i]) { + p_start++; + break; + } + } + + if (i == len) { + *sp = p_start; + break; + } + } + + if (**sp == '\0') { + *sp = NULL; + return *sp; + } + + while (**sp != '\0') { + for (i = 0; i < len; i++) { + if (**sp == delim[i]) { + **sp = '\0'; + break; + } + } + + (*sp)++; + if (i < len) { + break; + } + } + + return p_start; +}