Armchair Programming: writing a wildcard function (glob)
Programming is a bit like music - you can develop your skills while you're away from the keyboard. All you have to do is think! Recently I was wondering (in the shower, actually) how briefly I could write a wildcard function. So just as an exercise, I had a go... here's my attempt.
The aim isn't to implement grep or perl style globbing, but just a simple wildcard match on * and ? (something like SQL Server wildcards):
* means match zero or more characters
? means match any one character
Because this is an exercise in brevity, not performance, my version is recursive. Can you write a shorter version in C++?
bool WildMatch (const char *patt, const char *str)
{
while (*patt)
{
if (*patt == '*')
{
patt++;
while (*str)
if (WildMatch(patt, str))
return true;
else
str++;
}
else if ((*str) && ((*patt == '?') || (*patt == *str)))
{
patt++;
str++;
}
else
return false;
}
return (!*patt) && (!*str);
}
This posting is provided "AS IS" with no warranties, and confers no rights. Use of any included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm