部分名称搜索

时间:2013-12-08 09:26:08

标签: c++

有人可以举例说明如何部分名称搜索或使搜索不区分大小写。我键入这些函数来按姓氏搜索,但我想知道如何部分名称搜索/非区分大小写。谢谢

  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]);
    }

1 个答案:

答案 0 :(得分: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

相关问题