Last active
December 16, 2015 11:39
-
-
Save lingling2012/5429148 to your computer and use it in GitHub Desktop.
piece of code: try to reimplement 'strtok', 'strspn', 'strcspn' in Standard C Library.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* find index of first s1[i] that matches any s2[]. */ | |
size_t czf_strcspn(const char *s1, const char *s2) { | |
const char *sc1, *sc2; | |
for (sc1 = s1; *sc1 != '\0'; ++sc1) { | |
for (sc2 = s2; *sc2 != '\0'; ++sc2) { | |
if (*sc1 == *sc2) | |
return (sc1 - s1); | |
} | |
} | |
return (sc1 - s1); // terminating nulls match. | |
} | |
/* find index of first s1[i] that matches no s2[]. */ | |
size_t czf_strspn(const char *s1, const char *s2) { | |
const char *sc1, *sc2; | |
for (sc1 = s1; *sc1 != '\0'; ++sc1) { | |
for (sc2 = s2; ; ++sc2) { | |
if (*sc2 == '\0') { | |
return (sc1 - s1); | |
} else if (*sc1 == *sc2) { | |
break; | |
} | |
} | |
} | |
return (sc1 - s1); | |
} | |
/* find next token in s1[] delimited by s2[]. */ | |
char *czf_strtok(char *s1, const char *s2) { | |
char *sbegin, *send; | |
static char *ssave = ""; | |
sbegin = s1 ? s1 : ssave; | |
sbegin += czf_strspn(sbegin, s2); | |
if (*sbegin == '\0') { | |
ssave = ""; | |
return NULL; | |
} | |
send = sbegin + czf_strcspn(sbegin, s2); | |
if (*send != '\0') | |
*send++ = '\0'; | |
ssave = send; | |
return (sbegin); | |
} | |
int main(void) { | |
static char str[] = "git@github.com:user/repo.git"; | |
char *t; | |
t = czf_strtok(str, "@"); // t point to "git" | |
t = czf_strtok(NULL, ":"); // t point to "githut.com" | |
t = czf_strtok(NULL, "/"); // t point to "user" | |
t = czf_strtok(NULL, "."); // t point to "repo" | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment