問題描述
判斷包含萬用字元的匹配字串是否完全符合輸入的字串,匹配字串中包含的萬用字元僅有‘ * ’和‘?’,且萬用字元不會連續出現 。(要求完全符合,而不是包含)
其中,萬用字元‘ * ’:代替 0 個或多個字元,萬用字元‘ ? ’:代替一個字元
要求實現函數
int GetMatchSta (const char *ArrStr, const char *KeyStr)
【輸入】 ArrStr : 給定的字串
KeyStr : 包含萬用字元的匹配字串
【輸出】 無
【返回】是否匹配,匹配返回1 ,不匹配返回0
l 樣本
輸入: ” abcdefg”, “a*”
返回: 1
輸入: “tommababcabc” , t?m*ab*abc
返回: 1
參考了《代碼之美》第一章---Regex匹配器 :http://blog.chinaunix.net/uid-26822401-id-3150018.html
#include <iostream>#include <cstring>using namespace std;int GetMatchSta (const char *ArrStr,const char *KeyStr);int matchhere(const char *arrstr,const char *keystr);int matchstar(const char *arrstr,char ch,const char *keystr);//處理 * 的情況 int main(){char *arr="tommababcabc";char *key="t?m*ab*abc";cout<<GetMatchSta(arr,key)<<endl; } int GetMatchSta (const char *ArrStr,const char *KeyStr){if(KeyStr[0]=='*' && KeyStr[1]!='\0' && KeyStr[1]!='?')return matchstar(ArrStr,KeyStr[1],KeyStr+1);if(KeyStr[0]=='*' && (KeyStr[1]=='?'))// "*?" 這種情況匹配所有除非源串為空白 return strlen(ArrStr)!=0;if(KeyStr[0]=='*' && KeyStr[1]=='\0') // "*" 這情況匹配所有,包括空串 return 1;if(KeyStr[0]=='?')return matchhere(ArrStr+1,KeyStr+1);return matchhere(ArrStr,KeyStr); }int matchhere(const char *arrstr,const char *keystr){if(keystr[0]=='\0')return *arrstr=='\0';if(keystr[0]=='*')return matchstar(arrstr,keystr[1],keystr+1);if(*arrstr!='\0' && (keystr[0]==arrstr[0] || keystr[0]=='?'))return matchhere(arrstr+1,keystr+1);return 0;}int matchstar(const char *arrstr,char ch,const char *keystr){if(ch=='\0') return 1; //以 * 結尾 do{if(matchhere(arrstr,keystr))return 1;} while( *arrstr++ !='\0');return 0;}