字符串匹配通配符"*、?"

bool IsMatch(CString s, CString p)
{
    int j = 0;
    for (int i = 0, last_p = 0, s_start = 0; i < s.GetLength();)
    {
        if (j < p.GetLength() && (s[i] == p[j] || p[j] == '?'))//
        {
            i++;
            j++;
        }
        else if (j < p.GetLength() && p[j] == '*')
        {
            s_start = i;
            last_p = ++j;
        }
        else if (last_p != 0)
        {
            i = s_start++;
            j = last_p;
        }
        else
        {
            return false;
        }
    }
    for (; j < p.GetLength() && p[j] == '*'; ++j);
    return j == p.GetLength();
}

注:

*:匹配任意多个

?:匹配任意一个

形参

s:要搜索的字符串,例如:“a1b2c3”

p:匹配规则,例如:“a?b*”

 
作者:快雪
本文版权归作者所有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/kuaixue/p/15005913.html