2012-12-02 49 views
1

一直在处理这个程序,它需要使用一个函数来比较用户输入的字符串,并让用户有机会留下他/她不知道的字符输入,用*替换它们。该输入表示具有6个字符的汽车牌照(例如ABC123),并且允许用户离开任何这些字符(例如AB ** 23或** C12 *等)。所以函数需要返回与正确位置的字符匹配的所有对象,但如果A位于正确的位置,但其他字符不是,则它不能返回。但是,例如,用户只能输入A * * * * *,并且该函数应该返回所有A在第一个位置的对象。 我所做的是使用一个函数从输入字符串中删除所有星号,然后创建子字符串并将它们作为矢量发送给函数。需要比较字符串的某些元素

string removeAsterisk(string &rStr)// Function to remove asterisks from the string, if any. 
    { 
     stringstream strStream; 
     string delimiters = "*"; 
     size_t current; 
     size_t next = -1; 
     do 
    { 
     current = next + 1; 
     next = rStr.find_first_of(delimiters, current); 
     strStream << rStr.substr(current, next - current) << " "; 
} 
while (next != string::npos); 

return strStream.str(); 

}

 int main() 
    { 
      string newLicensePlateIn; 
      newLicensePlateIn = removeAsterisk(licensePlateIn); 
      string buf; // Have a buffer string 
      stringstream ss(newLicensePlateIn); // Insert the string into a stream 

      vector<string> tokens; // Create vector to hold our words 

      while (ss >> buf) 
       tokens.push_back(buf); 
      myRegister.showAllLicense(tokens); 
    } 

接收向量类功能目前看起来是这样的:

void VehicleRegister::showAllLicense(vector<string>& tokens)//NOT FUNCTIONAL 
    { 
     cout << "\nShowing all matching vehicles: " << endl; 
     for (int i = 0; i < nrOfVehicles; i++) 
     { 

      if(tokens[i].compare(vehicles[i]->getLicensePlate()) == 0) 
      { 
       cout << vehicles[i]->toString() << endl; 
      } 
     } 
    } 

如果有人明白我要做的,可能有一些想法,请随时回复,我希望有任何建议。 感谢您阅读本文档。A.

回答

0

只需遍历字符,逐个比较一个字符。如果其中一个字符是星号,则认为匹配,否则将它们进行比较以得到相等。例如:

bool LicensePlateMatch(std::string const & lhs, std::string const & rhs) 
{ 
    assert(lhs.size() == 6); 
    assert(rhs.size() == 6); 
    for (int i=0; i<6; ++i) 
    { 
     if (lhs[i] == '*' || rhs[i] == '*') 
      continue; 
     if (lhs[i] != rhs[i]) 
      return false; 
    } 
    return true; 
} 

实际上,您不必将其限制为6个字符。你可能想要允许洗手盆板。在这种情况下,只要确保两个字符串具有相同的长度,然后遍历所有字符位置,而不是在那里进行硬编码。

+0

这就是我正在寻找的问题,解决了问题。非常感谢。 –