搜索字符串数组

时间:2016-08-09 04:10:50

标签: c++ arrays string if-statement for-loop

所以我有一组存储在数组中的字符串,我想搜索数组,所以当找到字符串时,它应该说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;
         }  
}

所以每次我运行这个我总是被重定向到其他声明无论如何我都要解决这个问题

4 个答案:

答案 0 :(得分:2)

使用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::stringfirst_namestd::string数组,变量size存储数组大小。

答案 1 :(得分:1)

你正在打破其他部分。因此,例如,如果数组的大小为10,并且如果将userinput作为字符串存在于第5个数组元素中,则代码将在for循环的第一次迭代时中断。请尝试以下代码。如果找到匹配,它将打印&#34;找到&#34;,或者如果用户输入不在数组中,它将打印无效。希望能帮助到你。初始化&#34; first_name&#34;使用您的数组元素并更改大小。

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;

答案 2 :(得分:0)

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

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;

答案 3 :(得分:-1)

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

    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
相关问题