? 通配一个字符
* 通配零至多个字符
首先确定通配的字符串去掉*后,其长度比要匹配的字符串的长度小,这样就可以按照通配字符串来移动迭代器,而不必担心要匹配的字符串会越界。
第一个*以前的字符串要严格匹配,第一个*以后的字符串,要属于匹配字符串。
#include<iostream> #include<string> #include<list> #include<algorithm> using namespace std; struct Op { bool operator()(char a, char b) { if(b == '?') { return true; } else if( b == a) { return true; } else { return false; } } }; int main() { string youxing; string meixing; cin>>youxing>>meixing; //比较长度,避免后面担心匹配字符串越界 list<char>ltemp; ltemp.assign(youxing.begin(),youxing.end()); ltemp.remove('*'); if(ltemp.size()>meixing.size()) { cout<<"false"<<endl; return 0; } string::iterator iter1beg,iter1end,iter2beg,iter2end; iter1beg = youxing.begin(); iter2beg = meixing.begin(); iter1end = find(iter1beg,youxing.end(),'*'); //第一个*之前的字符串严格匹配 while(iter1beg!=iter1end) { if(*iter1beg != *iter2beg) { if(*iter1beg != '?') { cout<<"false"<<endl; return 0; } } ++iter1beg; ++iter2beg; } //第一个*以后的字符串要属于匹配字符串 while(iter1end != youxing.end() && (iter1end+1) != youxing.end()) { iter1beg = iter1end+1; iter1end = find(iter1beg,youxing.end(),'*'); iter2beg = search(iter2beg,meixing.end(),iter1beg,iter1end,Op()); if(iter2beg == meixing.end()) { cout<<"false"<<endl; return 0; } else { iter2beg = iter2beg + (iter1end-iter1beg); } } if(iter1end == youxing.end()) { if(iter2beg == meixing.end()) { cout<<"true"<<endl; } else { cout<<"false"<<endl; } } else if((iter1end+1) == youxing.end()) { cout<<"ture"<<endl; } return 0; }