部分名称搜索

Partial Name Search

本文关键字:搜索      更新时间:2023-10-16

有人能给我一个如何进行部分名称搜索或使搜索不区分大小写的例子吗。我键入了这些函数来按姓氏搜索,但我想知道如何进行部分名称搜索/不区分大小写。谢谢

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

您可以使用自定义函数进行字符串大小写不敏感比较:

#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