C language with wildcard matching algorithm

  • 2020-04-02 03:00:52
  • OfStack

Original code.

'? 'represents any single character, and' *' represents any zero or more characters. Often used for search matching of files.


bool MatchWithAsteriskW(wchar_t* str1, wchar_t* pattern)
{
  if (str1 == NULL) return false;
  if (pattern == NULL) return false;
  int len1 = lstrlenW(str1);
  int len2 = lstrlenW(pattern);
  int mark = 0;//A string separated by '*' and used to segment markup
  int p1 = 0, p2 = 0;
 
  while (p1<len1 && p2<len2)
  {
    if (pattern[p2] == '?')
    {
      p1++;
      p2++;
      continue;
    }
    if (pattern[p2] == '*')
    {
      
      p2++;
      mark = p2;
      continue;
    }
    if (str1[p1] != pattern[p2])
    {
      if (p1 == 0 && p2 == 0)
      {
        
        return false;
      }
      
      p1 -= p2 - mark - 1;
      p2 = mark;
      continue;
    }
    
    p1++;
    p2++;
  }
  if (p2 == len2)
  {
    if (p1 == len1)
    {
      
      return true;
    }
    if (pattern[p2 - 1] == '*')
    {
      
      return true;
    }
  }
  while (p2<len2)
  {
    
    if (pattern[p2] != '*')
      return false;
    p2++;
  }
  return true;
}

The above is all the content of this article, I hope you can enjoy it.


Related articles: