2013-12-08 111 views
1

有人可以舉例說明如何部分名稱搜索或使搜索不區分大小寫。我輸入這些函數來搜索姓氏,但我想知道如何部分名稱搜索/不區分大小寫。謝謝部分名稱搜索

int Search() 
    { 
     for(int i = 0 ; i < Size ; i++) 
      if (Target == List[i].LastName) 
       return i; 
     return -1; 
    } 
    void LookUp_Student() 
    { 
     string Target; 
     int Index; 
     cout << "\nEnter a name to search for (Last Name): "; 
     getline(cin,Target); 
     Index = Search(List,Size,Target); 
     if (Index == -1) 
      cout << Target <<" is not on the list.\n" ; 
     else 
      Print_Search(List[Index]); 
    } 
+0

你可能會發現這個問題和答案有幫助http://stackoverflow.com/questions/313970/stl-string-to-lower-case至少對於不區分大小寫的方面 – mathematician1975

+0

使用toupper(或tolower)使其不區分大小寫。然後使用find來搜索字符串中的子字符串。 –

回答

0

您可以使用自定義功能做一個字符串大小寫不敏感的比較:

#include <algorithm> 
//... 
bool compare_str(const string& lhs, const string& rhs) 
{ 
    return lhs.size() == rhs.size() && 
      std::equal(lhs.begin(), lhs.end(), rhs.begin(), 
       // Lambda function 
       [](const char& x, const char& y) { 
       // Use tolower or toupper 
        return toupper(x) == toupper(y); 
        } 
       ); 
} 

,然後用它喜歡:

if (compare_str(Target,List[i].LastName)) 
{ 
// a match 
} 

編號:std::equal