2

I have been writing a recursive wildcard matching algorithm in c++. But I'm having trouble completing it. Here look at what I write so far.

? matches any character, * matches any string

bool WildCardMatch(char *str, char *match){
 while (*match){
    if (*match =='?'){
        if (!*str){
            return false;
        }
        str++; 
        match++;
    }
    else if (*match == '*'){
        if (WildcardMatch(str, match + 1)){
            return true;
        }
        return false;
    }
 }
return !*str && !*match;
}

What's wrong with my algorithm? How should I fix it? Or can anyone suggest me a better solution for recursive wildcard matching algorithm?

1
  • What are the symptoms? Commented Aug 12, 2015 at 10:26

1 Answer 1

2

Here look at this recursive wildcard matching algorithm. It will solve your troubles.

bool WildcardMatch(const TCHAR *pszString, const TCHAR *pszMatch){
while (*pszMatch)
{
    if (*pszMatch == _T('?'))
    {
        if (!*pszString)
            return false;

        ++pszString;
        ++pszMatch;
    }
    else if (*pszMatch == _T('*'))
    {
        if (WildcardMatch(pszString, pszMatch + 1))
            return true;

        if (*pszString && WildcardMatch(pszString + 1, pszMatch))
            return true;

        return false;
    }
    else
    {
        if (::CharUpper(MAKEINTRESOURCE(MAKELONG(*pszString++, 0))) != ::CharUpper(MAKEINTRESOURCE(MAKELONG(*pszMatch++, 0))))
            return false;
    }
}

return !*pszString && !*pszMatch;
}
Sign up to request clarification or add additional context in comments.

3 Comments

whats the time complexity?
@user1846749 For strings without *, linear. For strings with *, exponential with regard to the number of asterisks. See the discussion for the "ABORT" modification from 1993 in en.wikipedia.org/wiki/….
@user1846749 Alright, I've done porting the ABORT thing to this sample. See repl.it/repls/ScarceMinorTechnician.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.