Question
Does a given file name match a single - star pattern ? (Do not use regex)
index.html matches *.html
foo.txt does not match *.html
matches(“index.html”, “*html”) returns true
matches(“foo.txt”, “*html”) returns false
matches(“cat”, “c*t”) returns true
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Match words.
Created Date : 20-01-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <regex>
using namespace std;
bool StartWith(string str1, string str2)
{
if (str2.empty()) return false;
int index1(0);
int index2(0);
while (index1 < str1.size() && index2 < str2.size()){
if (str1[index1 ++] != str2[index2++]) break;
}
return (index2 == str2.size()) ? true : false;
}
bool EndWith(string str1, string str2)
{
if (str2.empty()) return false;
int index1 = str1.size() - 1;
int index2 = str2.size() - 1;
while (index1 >= 0 && index2 >= 0){
if (str1[index1--] != str2[index2--]) break;
}
return (index2 == -1) ? true : false;
}
bool Matches1(string str1, string str2)
{
if (str1 == str2) return true;
if (str2.size() < 1 ||
str1.size() < str2.size() - 1) return false;
auto index = str2.find('*');
if(index == string::npos){
throw invalid_argument("Invalid input!");
}
else if (index == 0){
return EndWith(str1, str2.substr(1));
}
else if (index == str2.size() - 1){
return StartWith(str1, str2.substr(0, str2.size() - 1));
}
else{
return StartWith(str1, str2.substr(0, index)) &&
EndWith(str1, str2.substr(index + 1));
}
}
int main()
{
cout << std::boolalpha << Matches1("index.html", ".*html") << endl;
cout << std::boolalpha << Matches1("foo.txt", ".*html") << endl;
cout << std::boolalpha << Matches1("cat", "c.*t") << endl;
return 0;
}
Output
true
false
true
Press any key to continue . . .