如何在C ++中搜索字符串数组

时间:2013-03-25 02:33:03

标签: c++ string search

我希望能够在C ++中搜索字符串数组。我有这些数据:

"Foo Becky, 924-334-2514", 
"Becky Warren, 555-1223", 
"Geri Palmer, 555-8787", 
"Ron Palmer, 555-2783"

如果用户键入Bec,程序将找到名称Foo Becky, 924-234-2314。如果用户输入Palmer,则该计划应显示Geri Palmer, 555-8787Ron Palmer, 555-2783

这是我到目前为止所做的:

#include <iostream>
#include <string>
using namespace std;
int main(){
    int n;
    string search;

    while(1){
        cout << "How many data you want to input: "<< endl;
        cin >> n;
        cin.ignore(1000, 10);

        if(n > 0 && n < 20){
            break;
        }
        cout << "Number of data can not be negative or more than 20. "<< endl;
    }

    string* data = new string[n];

    for(int i=0; i< n; i++){
        cout << "Enter [First Name] [Last Name], [Phone-Number] and then hit "
             << "enter." << endl << "e.g: Foo Becky, 925-245-413"<< endl;
        getline(cin,data[i]);
        cout << endl;
    }

    cout << "Enter what you want to search for: "<< endl;
    getline(cin, search);

    for(int i =0; i< n; i++){
        if(search == data[i]){
            cout << data[i]<< endl;
        }
    }
    delete [] data;
    return 0;
}

如何在C ++中搜索字符串数组?

3 个答案:

答案 0 :(得分:1)

您必须使用std::string的{​​{3}}方法。此函数返回在搜索到的字符串中搜索的字符串的开始位置。如果未找到匹配项,则返回find女巫实际上只是-1

if(data[i].find(search, 0) != std::string::npos);
{
    cout << data[i]<< endl;
}

答案 1 :(得分:1)

你应该使用find,就像已经提到的A4L一样。我只想补充一点,如果输入了错误的值,你对cin.ignore的使用将无法正常工作。你需要

cin.clear() 

也。有关详细信息,请参阅this link

答案 2 :(得分:0)

如何在C ++中搜索字符串数组示例:

这是强力搜索方法。蛮力意味着我们逐步遍历整个字符串数组,并在数组的每个索引处搜索匹配的字符串。

#include<iostream>
#include<string>
using namespace std;
int main(){
    //Create a structure to hold the data:
    string data[] = {"pidgeon", "abcd", "1234", "%^*#"};

    //Get the length of the array.
    int size = 4;

    //loop through all the items and print them if they match
    string matchString = "bc";
    for(int x = 0; x < size; x++){
        if (data[x].find(matchString, 0) != std::string::npos){
            cout << data[x] << endl;
        }
    }
}

以上代码打印:

abcd

你应该在头脑中自上而下地描述上面的代码:

一个名为data的字符串数组被初始化为包含4个元素,并给出了四个值pidgeonabcd1234%^&#。创建一个名为size的int变量,它表示字符串数组中的元素数。创建一个名为matchString的字符串变量,其中包含字符串'bc'。

for循环索引从位置0开始并递增1,直到它达到小于数组大小的值。因此for循环遍历:0,1,2,3.x的第一个值是0. if语句将data [0]解析为pidgeon。对该字符串应用find方法,并传入两个参数。要匹配的字符串,以及要在搜索(0)中考虑的字符串中第一个字符的位置。

如果'pidgeon'中存在'bc',那么它将返回第一个匹配的第一个字符的位置,否则它将打印std :: string:npos,这是size_t指定未找到的最大值。

pidge中不存在

bc因此它会跳过for循环的内部。 for循环继续索引位置1.bc包含在abcd中。这样打印出字符串。搜索完所有项目后,for循环结束,程序完成。

相关问题