nanjero05
nanjero05

Reputation: 111

C++ How can I compare a user input to a list of string with strict ordering?

I am trying to create a search array function where I have a list of string and I take a user input. I then compare the user input to the strings in the array and output any that matches any string in exact order of the input. I am not sure where to start. like so:

array: "this", "is", "a", "test"

user input: "t"

The output should then be "this" and "test"

This is what i have so far:

string arr[6] = {"hello", "this", "is", "a", "test", "string"};
vector<string> words;
for (int i=0; i<5; i++) {
    if (a.find(arr[i]) != string::npos) {
        words.push_back(arr[i]);
    }
}

for (int i=0; i<words.size(); i++) {
    cout << words[i] << endl;
}

at the moment it only searches for exact matches. How could i make it to the scenario described above?

Upvotes: 0

Views: 1287

Answers (2)

ATul Singh
ATul Singh

Reputation: 532

Change this

if (a.find(arr[i]) != string::npos) 

to

if (arr[i].find(a) != string::npos) 

You will search your User string in the List of strings one by one.

Upvotes: 1

Rakete1111
Rakete1111

Reputation: 49008

There is a logic error in the code you posted, here: if (a.find(arr[i]) != string::npos) {, it searches the input string for the words in the array, but you want to find the input string in the words of the array (as far as I understood).

Apart from that, I would rather use std::array and for each loops:

Upvotes: 0

Related Questions