简体   繁体   中英

How to do a partial prefix search in c++?

I'm trying to create a Phonebook program that I can search through with a partial prefix. The program goes through a .txt file and asks the user who they want to search for. Example of .txt file:

Captain-Crunch 123-456-7890
Silly-Goose 234-456-7891
Some-Dude 890-234-5679

etc

I want to be able to search 'S' and it will give me the first instance it finds, so "Silly-Goose 234-456-7891" for example. The code I have now does this, but let's say I enter 'G', it will also return "Silly-Goose 234-456-7891". I just want the partial prefix search to match up with the first letters, and not search for just any instance for what I searched.

Current code:

    string search;
    string line, name, number;
    int count = 0;
    size_t found;
    
   
    cout << "Please enter person to search for: ";
    cin >> search;
    
    
    if(search == "."){
        cout << "Thank you for using this program!" << endl;
        exit(0);
    }
    
    while (getline(inFile, line))
    {
        inFile >> name;
        inFile >> number;
        found = name.find(search);
        if (found = !string::npos){
            cout << name << " " << number << endl;
            break;
        }
    }

Right now, you're searching for name.find(search) != string::npos which means "is name in search".

According to this site string::find "returns the position of the first character of the found substring or npos if no such substring is found". What does that mean? Basicly it returns the offset of the substring in the string you searched for. In your case, you want that result to be 0 (your character would be at the start of the chain).

So, as @NathanOliver already suggested, the solution would be to replace

if(found != string::npos)

by

if(found == 0)

C++20 added std::basic_string::starts_with for this purpose:

if (name.starts_with(search)) {
  // found
}

Note that std::string is a std::basic_string .

-> Demo

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