Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:49:13

0001 // name=match ; gcc $name.cc -lstdc++ -o /tmp/$name && /tmp/$name
0002 
0003 #include <cassert>
0004 
0005 /**
0006 match
0007 -------
0008 
0009 Based on https://www.geeksforgeeks.org/wildcard-character-matching/
0010 
0011 The second argument string can contain wildcard tokens:
0012 
0013 `*` 
0014      matches with 0 or more of any char (NB '**' not supported)
0015 `?`   
0016      matches any one character.
0017 `$`
0018      when appearing at end of q signifies the end of s 
0019 
0020 **/
0021 
0022 bool match(const char* s, const char* q) // q may contain wildcard chars ? * 
0023 {
0024     if (*q == '\0' && *s == '\0') return true;
0025 
0026     if (*q == '*' && *(q+1) != '\0' && *s == '\0') return false;  // reached end of s but still q chars coming 
0027 
0028     if (*q == '$' && *(q+1) == '\0' && *s == '\0' ) return true ; 
0029 
0030     if (*q == '?' || *q == *s) return match(s+1, q+1);  // on to next char
0031 
0032     if (*q == '*') return match(s, q+1) || match(s+1, q);  // '*' can match nothing or anything in s, including literal '*'
0033 
0034     return false;
0035 }
0036 
0037 int main()
0038 {
0039     assert( match("hello", "hello" )); 
0040     assert( match("hello", "he*llo" ));  // '*' matches nothing 
0041     assert( match("hello", "hello*" )); 
0042     assert( match("hello", "hell*" )); 
0043     assert( match("hello", "hell?" )); 
0044     assert( match("hello", "?????" )); 
0045     assert( match("hello", "?ell?" )); 
0046     assert( match("hello", "he?lo" )); 
0047     assert( match("hello", "he*" )); 
0048     assert( match("hello", "he*lo" )); 
0049 
0050     assert(!match("hello", "????" )); 
0051 
0052     assert( match("he*lo", "he*lo" )); 
0053     assert( match("he*lo", "he*lo" )); 
0054 
0055     assert( match("hello", "hello$")) ; 
0056     assert( !match("helloworld", "hello$")) ; 
0057 
0058 }
0059