搜索字符串数组
searching through a array of string
所以我有这组字符串存储在一个数组中,我想搜索数组,所以当字符串被找到时,它应该说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::set
和std::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...
对于您的示例,一切都很好,如果userInput
是std::string
, first_name
是std::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
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- C++ 对象数组字符串输入在控制台上不起作用
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 无法区分 JSON 对象/数组/字符串
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何使用数组字符串进行输入验证
- (C++) 打印字符数组字符串的单词时出现问题
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- C 函数反转字符数组字符串
- 如何在 c++ 中创建数组(字符串 [] )的向量
- 如何返回数组字符串的指针
- char数组字符串混淆
- 如何从字符数组字符串中提取空格
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- C++数组字符串函数
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递
- visual将音频文件存储到数组/字符串流C++中
- c++在char数组(字符串)上将what替换为
- 将数组字符串转换为intger c++(初学者)
- 需要设置数组字符串长度,使其恰好为13