HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Wildcard search in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wildcardsearchstackoverflow

Problem

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.

Solution

You should the parameters for null values. strlen() does not tolerate nulls passed to it as parameters.

I'm not a complete zealot when it comes to the use of goto, but I'm not sure what benefit it gives in this code. Replacing the gotos with return true or return false would make the code a little simpler and more readable.

if (no_match) {
       goto no_match;
  }


compared to this for example:

if (no_match)
     return false;


For the bug you mentioned you will need to compare the lengths of the first and second wildcard parameters IF there is no special character in the second parameter.

Code Snippets

if (no_match) {
       goto no_match;
  }
if (no_match)
     return false;

Context

StackExchange Code Review Q#30456, answer score: 3

Revisions (0)

No revisions yet.