In the effort to improve my C knowledge, I tried creating a wildcard search function:
bool wildcard(char *value, char *wcard) {
size_t vsize = strlen(value);
size_t wsize = strlen(wcard);
bool no_match = false;
if (wsize > vsize) {
return false;
}
for (int w = 0, v = 0; w < wsize; w++, v++) {
switch (wcard[w]) {
case MULTICHAR:
if (w == wsize) {
goto match;
} else {
w++;
while (v < vsize) {
if (wcard[w] == value[v++]) {
v--;
break;
}
}
if (no_match) {
goto no_match;
}
}
break;
case ONECHAR:
break;
default:
if (wcard[w] != value[v]) {
goto no_match;
}
}
}
match:
return true;
no_match:
return false;
}
I have tested this by doing:
printf("Result: %d <- Should be true\n",wildcard("Hello World","Hello*"));
printf("Result: %d <- Should be true\n",wildcard("Hello World","*Hello*"));
printf("Result: %d <- Should be true\n",wildcard("Hello World","He?lo*"));
All return 1.
You can see the project here.
Any tips or improvements are welcome.
Note
I've already found a bug. If the wcard in present in the string, it will return true
even if there is more data there.
Example:
wildcard("Hello World","Hello")
This will return true
when it shouldn't.
fnmatch()
function. \$\endgroup\$