带有通配符的字符串和另一个字符串进行匹配

来源:互联网 发布:为什么选择java 编辑:程序博客网 时间:2024/04/27 23:40

先吐个槽吧,公司也有这个算法,看了半天也不知道干什么呢,写的非常复杂,偶然的发现一个算法,小巧而精密,下面详细叙述:

* 可以匹配0个或0个以上的字符

?可以匹配一个字符


这个算法应用的是递归的算法,开始担心如果字符串过长的话,会因递归引起栈的溢出,还好在网上查了一下,win32默认的递归栈大小是2M,这足以进行很长字符串的匹配。

下面是核心的代码,思路都在代码的注释中,下面给出代码:

#include<iostream>#include<string>using namespace std;bool match(char *pattern, char *content) {// if we reatch both end of two string, we are doneif ('\0' == *pattern && '\0' == *content)return true;/* make sure that the characters after '*' are present in second string.      this function assumes that the first string will not contain two       consecutive '*'*/if ('*' == *pattern && '\0' != *(pattern + 1) && '\0' == *content)return false;// if the first string contains '?', or current characters of both     // strings matchif ('?' == *pattern || *pattern == *content)return match(pattern + 1, content + 1);/* if there is *, then there are two possibilities       a) We consider current character of second string       b) We ignore current character of second string.*/if ('*' == *pattern)return match(pattern + 1, content) || match(pattern, content + 1);return false;}void test(char *pattern, char *content) {if (NULL == pattern || NULL == content)puts("no");match(pattern, content) ? puts("yes") : puts("no");}int main(int argc, char *argv[]) {test("g*ks", "geeks"); // Yes    test("ge?ks*", "geeksforgeeks"); // Yes    test("g*k", "gee");  // No because 'k' is not in second    test("*pqrs", "pqrst"); // No because 't' is not in first    test("abc*bcd", "abcdhghgbcd"); // Yes    test("abc*c?d", "abcd"); // No because second must have 2 instances of 'c'    test("*c*d", "abcd"); // Yes    test("*?c*d", "abcd"); // Yescin.get();    return 0;}


原创粉丝点击