简体   繁体   中英

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?

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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM