试图对字符串执行索引搜索

trying to perform an index search for string

本文关键字:索引 搜索 执行 字符串      更新时间:2023-10-16

我试图写一个代码,应该允许我搜索数组的字符串,我输入时提示。该程序要求用户输入一定数量或数据,然后要求用户执行搜索。我有一个艰难的时间搜索输入。我可以做到这一点与整数,但现在字符串请帮助。你会怎么做呢?

#include <iostream>
using namespace std;
void contactArray(string a[], int size);
string search(const string a[], int size, string find);
int main( )
{
    cout << "This program searches a list .n";
    const int arraySize = 3;
    string a[arraySize];
    contactArray(a, arraySize);
    string find;
    cout << "Enter a value to search for: ";
    cin >> find;
    string lookup = search(a, arraySize, find);
    if (lookup == " ")
        cout << find << " is not in the array.n";
    else
        cout << find << " is element " << lookup << " in the array.n";
    return 0;
}
void contactArray(string a[], int size)
{
    cout << "Enter " << size << " list.n";
    for (int index = 0; index < size; index++)
        cin >> a[index];
}
int search(const string a[], int size, string find)
{
    string index = "";
    while ((a[index[3]] != find) && (index < size))
        cout<<"try again"<<endl;
    if (index == find)        
        index = "";
    return index;
    cout<<"hgi";
}

你可以用整数做吗?用整数来做,用字符串来调用这个函数,当你得到一个cannot convert string to int编译错误时,把int这个词改成string

代替

int search(const string a[], int size, string find)
{
    string index = "";
    while ((a[index[3]] != find) && (index < size))
        cout<<"try again"<<endl;
    if (index == find)        
        index = "";
    return index;
    cout<<"hgi";
}

试试

int search(string a[], int size, string find)
{
      int index = -1;
      for(int i=0;i<size;i++)
      {
         if(a[i] == find)
         {
             index = i;
             break;
         }
      }
      return index; 
}

如果函数返回-1,表示没有找到字符串。任何其他返回值是'find'字符串在数组中所在的位置。

使用for循环遍历数组并检查值是否在数组中。可能有一个c++函数来做这个cstdlib,我知道。net有这个内置的