Implemented strtok()

This commit is contained in:
Max Wash
2021-02-19 13:54:35 +00:00
parent 2afef81c45
commit 2c197ead3e
2 changed files with 65 additions and 0 deletions

View File

@@ -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

View File

@@ -0,0 +1,62 @@
#include <string.h>
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;
}