[ create a new paste ] login | about

Link: http://codepad.org/vdkJgqw6    [ raw code | output | fork | 2 comments ]

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:
1
2
3
4
5
6
7
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


Create a new paste based on this one


Comments:
posted by vectorio on Dec 9
The following test yields false, but one would expect true:

test_wildcard("ab*d", "abcdd");
reply
posted by vectorio on Dec 9
I believe this criterion to be the cause:

while(*source != *pattern){}

If source and pattern are equal again, it does not mean that the wild card no longer applies.
reply