AaronMiller
-
C,
pasted
on Nov 8:
|
// includes
#include <stdio.h>
// perform the pattern test
int wildcard(const char *source, const char *pattern) {
while(1) {
//wildcard
if (*pattern=='*') {
// skip pattern while it's equal to '*'
while(*pattern=='*')
pattern++;
// accept the rest of the string if the pattern ends in "*"
if (*pattern==0)
return 1;
// enumerate the source string
while(*source != *pattern) {
// did the source string terminate?
if (*source==0)
// not what was wanted
return 0;
// okay, increment the source string
source++;
}
// continue the loop
continue;
}
// is the source character not equal to the pattern character?
if (*source != *pattern)
break; //break to keep the compiler happy
// they're equal, is it a null termination?
if (*source==0)
return 1;
// okay, there's more to the string, increment each
source++;
pattern++;
}
// not equal, return zero
return 0;
}
// run a test
void test_wildcard(const char *string, const char *pattern) {
int r;
r = wildcard(string, pattern);
fprintf(stdout, "wildcard(\"%s\", \"%s\") == %s\n",
string, pattern, r?"true":"false");
fflush(stdout);
}
// main function
int main(int argc, char **argv) {
if (argc||argv) {/*unused*/}
test_wildcard("hello, world!", "*llo, wor*");
test_wildcard("abcd", "abcd*");
test_wildcard("/src/something.c", "/src/*.c");
test_wildcard("fragment.vert", "*.vert");
test_wildcard("fragment.frag", "*.vert");
test_wildcard("vertex.frag.vert", "*.frag");
test_wildcard("abcd", "abcd");
return 0;
}
|
Output:
|
wildcard("hello, world!", "*llo, wor*") == true
wildcard("abcd", "abcd*") == true
wildcard("/src/something.c", "/src/*.c") == true
wildcard("fragment.vert", "*.vert") == true
wildcard("fragment.frag", "*.vert") == false
wildcard("vertex.frag.vert", "*.frag") == false
wildcard("abcd", "abcd") == true
|
|