題目:在一篇英文文章中查找指定的人名,人名使用二十六個英文字母(可以是大寫或小寫)、空格以及兩個通配符組成(*、?),通配符“*”表示零個或多個任意字母,通配符“?”表示一個任意字母。
如:“J* Smi??” 可以匹配“John Smith” .
請用C語言實現如下函數:
void scan(const char* pszText, const char* pszName);
注:pszText爲整個文章字符,pszName爲要求匹配的英文名。
請完成些函數實現輸出所有匹配的英文名,除了printf外,不能用第三方的庫函數等。
#include<iostream.h>
const char *pEnd=NULL; //記錄匹配成功後結束的位置,方便輸出
bool match(const char *pszText,const char *pszName)
{
if(*pszName=='\0') //匹配到字符串結尾,匹配成功
{
pEnd=pszText;
return true;
}
if(*pszText=='\0') //文本到達末尾
{
if(*pszName=='*') //如果字符串末尾爲*則說明可以匹配
//否則,匹配失敗
{
pEnd=pszText;
return true;
}
return false;
}
if(*pszName!='*'&&*pszName!='?')
{
if(*pszText==*pszName)
return match(pszText+1,pszName+1);
return false;
}
else
{
if(*pszName=='*')
return match(pszText,pszName+1)||match(pszText+1,pszName);//繼續匹配文本的0個或者多個字符
else
return match(pszText+1,pszName+1);
}
}
void scan(const char *pszText,const char *pszName)
{
while(*pszText!='\0')
{
if(match(pszText,pszName))
{
while(pszText!=pEnd)
cout<<*pszText++;
cout<<endl;
}
pszText++;
}
}
void main()
{
char psztext[]="we are the world,we are the child?John Smith say.but the Jay Smisi",
pszname[]="J* Smi??";
scan(psztext,pszname);
}