搜索字符串数组

searching through a array of string

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

所以我有这组字符串存储在一个数组中,我想搜索数组,所以当字符串被找到时,它应该说found,当它没有找到时,它应该说invalid这是我目前看到的

cout << "Enter a Name to Search" <<endl;
cin >>userInput;
for (int i=0; i<size; i++)
{
   if (first_name[i]==userInput)
    {
        cout <<"Found"<<endl;
    }else{
          cout << "InValid"<<endl;
            break;
         }  
}

所以每次我运行这个,我总是被重定向到else语句是有我修复这个

使用std::setstd::unordered_set等容器进行快速搜索。

#include <iostream>
#include <unordered_set>
#include <string>
int main()
{
    std::unordered_set<std::string> first_name;
    first_name.insert("Joe");
    first_name.insert("Anderson");
    //....
    std::string input;
    std::cin >> input;
    std::unordered_set<std::string>::iterator searchResult = first_name.find(input); // Search for the string. If nothing is found end iterator will be returned
    if(searchResult != first_name.end())
        std::cout << "Found!" << std::endl;
    else
        std::cout << "Not found!" << std::endl;
}

输入"Joe"时的程序输出:

Found!
Press <RETURN> to close this window...

对于您的示例,一切都很好,如果userInputstd::string, first_namestd::string和可变size存储数组大小的数组。

您正在从else部分中断。因此,例如,如果数组的大小为10,并且如果您将userinput作为第5个数组元素中的字符串,那么您的代码将在for循环的第一次迭代时中断。试试下面的代码。如果找到匹配,它将打印"found",或者如果用户输入不在数组中,它将打印无效。希望能有所帮助。用你的数组元素初始化"first_name"并改变它的大小。

string userInput;
string first_name[10];
int i=0;
int size = 10;
first_name[0] = "Hi";
first_name[1] = "Hii";
first_name[2] = "Hiii";
cout << "Enter a Name to Search" <<endl;
cin >> userInput;
for (i = 0; i<size; i++)
{
    if (first_name[i] == userInput)
    {
        cout <<"Found"<< endl;
        break;
    }
}
if(i == size)
    cout << "Invalid" << endl;

我认为更优雅的解决方案是使用布尔标志,如:

cout << "Enter a Name to Search" <<endl;
cin >>userInput;
bool found = false;
for (int i=0; i<size; i++)
{
  if (first_name[i]==userInput)
  {
     found = true;
     break;
  }
}
cout << (found?"found":"invalid") << endl;

所以我能够找到一个解决方案这就是我所做的

    string result =""; //set a string named result 
    cout << "Enter a Name to Search" <<endl;
    cin >>userInput;
    for (int i=0; i<size; i++)
    {
       if (!(first_name[i]==userInput))
        {
           result = "Found";
            break;
        }else{
              result ="InValid";
             }  
    }
     cout <<result<<endl;  //outside of for loop