【每日面试题】字符串通配符匹配问题

题目:在一篇英文文章中查找指定的人名,人名使用二十六个英文字母(可以是大写或小写)、空格以及两个通配符组成(*、?),通配符“*”表示零个或多个任意字母,通配符“?”表示一个任意字母。
如:“J* Smi??” 可以匹配“John Smith” .

请用C语言实现如下函数:
void scan(const char* pszText, const char* pszName);
注:pszText为整个文章字符,pszName为要求匹配的英文名。
请完成些函数实现输出所有匹配的英文名,除了printf外,不能用第三方的库函数等。

 代码:

#include "stdafx.h"
#include<stdio.h>
const char *p=NULL;
bool match(const char* ptext,const char* name)  /* 字符串匹配函数,使用递归的调用方法*/
{
   if(*name=='\0')
   {
          p=ptext;
    return true;
   }
   if(*ptext=='\0')
   {
    if(*name=='*'&&*(name+1)=='\0')
    {
     p=ptext;
     return true;
    }
    return false;
   }
   if(*name!='*'&&*name!='?')
   {
    if(*name==*ptext)
    return  match(ptext+1,name+1);
    return false;
   }
   else
   {
    if(*name=='*')
     return match(ptext+1,name)||match(ptext,name+1);
    else
    {
     return match(ptext+1,name+1);
    }
   }
}
void scan(const char* ptext,const char* name)
{
 while(*ptext!='\0')
 {
    if(*ptext==*name)
 {
 bool flag=match(ptext,name);
 if(flag)
 {
  while(ptext!=p)
  {
   printf("%c",*ptext++);
  }
  printf("\n");
 }
 }
 else
  ptext++;
 }
}
int main()
{
 char ptext[100]={0};
 char pname[100]={0};
     gets(ptext);
  gets(pname);
     scan(ptext,pname);
 return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章