检查字符串是否与字符串数组中的任何字符串匹配

Checking a string matches any string in a string array?

本文关键字:字符串 任何 字符 串匹配 数组 是否 检查      更新时间:2023-10-16

我正在寻找一种方法来检查用户在提示时输入的字符串(让它是一个字符串变量"userinput")从一个包含10个其他字符串的数组。到目前为止,我有:

    while (userinput.empty()) //Check for empty input
{
    cout << "Please enter your identity.n"; //Identify user
    getline(cin, userinput);
    do //Check to see if user is the same as the string variable "user"
    {
    cout << "This user is either non existent or has access privileges revoked.n"; //Wrong username!
    cout << "Please re-enter the username.n";
    getline(cin, userinput);
    }
    while (user != userinput);
}

可以看到,这只适用于单个字符串变量"user"。对于字符串数组,我该如何改变它呢?

数组本身如下:

string arr[10] = {"Test1", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7", "Test8", "Test9", "Test10"};

请注意:我不打算使用密码,只使用用户名。

您可以这样使用内置的count函数:

do{
    getline(cin, userinput);
}
while(!std::count(arr, arr+10, userinput));

也在ideone上。

你的循环应该是这样的:

cout << "Please enter your identity.n"; //Identify user
getline(cin, userinput);
while (!std::count(arr, arr+10, userinput)) //Check to see if user is the same as the string variable "user"
{
    cout << "This user is either non existent or has access privileges revoked.n"; //Wrong username!
    cout << "Please re-enter the username.n";
    getline(cin, userinput);
}

你可以在这里看到

将检查放在单独的函数中

 bool isValidUserName(const string& input) {
      for(int i = 0; i < 10; ++i) {
          if(input == arr[i]) {
              return true;
          }
      }
      return false;
 }

并将其用作while

中的条件
 while (!isValidUserName(userinput));

如果您有大量字符串要比较,那么使用哈希映射(std::unordered_set)而不是数组会更有效。在哈希表中查找要比在数组中查找快得多。

unordered_set<string> valid_inputs {"Test1", "Test2", "Test3", "Test4", "Test5", "Test6"};

然后你可以用这样的方式检查用户输入:

if (valid_inputs.find(user_input) == valid_inputs.end())
  cout << "error";
else
  cout << "success";
相关文章: