【问题标题】:trying to perform an index search for string尝试对字符串执行索引搜索
【发布时间】:2011-12-16 03:43:24
【问题描述】:

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

#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";
}

【问题讨论】:

  • 这是作业吗?如果是这样,请添加homework 标签

标签: c++ visual-c++


【解决方案1】:

你可以用整数来做吗?使用整数执行此操作,使用字符串调用该函数,无论您遇到cannot convert string to int 编译器错误,请将单词int 更改为string。应该几乎一模一样。

【讨论】:

    【解决方案2】:

    而不是

    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,则表示未找到该字符串。任何其他返回都是数组中“查找”字符串所在的位置。

    【讨论】:

      【解决方案3】:

      使用 for 循环遍历数组并检查值是否在数组中。可能有一个 C++ 函数来执行此 cstdlib,我知道 .Net 内置了它。

      【讨论】:

        猜你喜欢
        • 2020-05-05
        • 2019-12-22
        • 2017-07-23
        • 1970-01-01
        • 1970-01-01
        • 2015-03-12
        • 2019-09-08
        • 2012-05-09
        • 2019-12-02
        相关资源
        最近更新 更多