Created
August 9, 2016 21:22
-
-
Save a-square/b85f50b44d2a3d319c0ac61395468efc to your computer and use it in GitHub Desktop.
Matches a string against a string set, tells you which one it matched
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
#include <stdio.h> | |
#include <stdlib.h> | |
/* | |
* matches str to one of the strings in set (at most 32), | |
* returns the matched string or NULL | |
*/ | |
char* strset(char** set, char* str) { | |
char* mset[32]; | |
char** msetcur; | |
char** setcur; | |
char** msetend; | |
char* msetstr; | |
char c; | |
size_t i; | |
if (!str || !set || !*set) { | |
return NULL; | |
} | |
msetcur = mset; | |
setcur = set; | |
while ((*msetcur++ = *setcur++)) | |
continue; | |
msetend = msetcur - 1; | |
i = 0; | |
do { | |
c = str[i]; | |
for (msetcur = mset; (msetstr = *msetcur); ) { | |
if (msetstr[i] == c) { | |
++msetcur; | |
} else { | |
*msetcur = *--msetend; | |
*msetend = NULL; | |
} | |
} | |
if (!*mset) { | |
return NULL; | |
} | |
++i; | |
} while (c); | |
return *mset; | |
} | |
int main() { | |
char* set[] = {"foo", "bar", "baz", NULL}; | |
printf("%s: %s\n", "foo", strset(set, "foo")); | |
printf("%s: %s\n", "bar", strset(set, "bar")); | |
printf("%s: %s\n", "baz", strset(set, "baz")); | |
printf("%s: %s\n", "ba_", strset(set, "ba_")); | |
printf("%s: %s\n", "bazz", strset(set, "bazz")); | |
printf("%s: %s\n", "fo", strset(set, "fo")); | |
printf("%s: %s\n", "", strset(set, "")); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment