1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <string>
#include <regex>
#include <vector>
#include <iostream>
// looks for case-insensitive matches for beginning of first names, last names
// invariant: names are of the form first_name white space last_name ie. ^\S+\s+\S+$, user_input is alphanumeric
void search_for_names( const std::string names[], std::size_t num_names, std::string user_input,
std::vector<std::string>& matched_first_names, std::vector<std::string>& matched_last_names )
{
const std::regex first_name_re( user_input + ".*", std::regex::icase ) ; // begins with user_input
std::regex last_name_re( "\\S+\\s+" + user_input + ".*", std::regex::icase ) ; // second name begins with user_input
matched_first_names.clear() ;
matched_last_names.clear() ;
// if( user_input.empty() ) return ; // uncomment if empty input does not match the beginning of any string
for( std::size_t i = 0 ; i < num_names ; ++i )
{
if( std::regex_match( names[i], first_name_re ) ) matched_first_names.push_back( names[i] ) ;
if( std::regex_match( names[i], last_name_re ) ) matched_last_names.push_back( names[i] ) ;
}
}
int main() // a minimal test driver
{
std::string names[] = { "Bugs Bunny", "Daffy Duck", "PORKY Pig", "pig porky", "Elmer Fudd", "Daft Daffodil", "Coy coyote", "Wile Coyote" } ;
const std::size_t N = sizeof(names) / sizeof(*names) ;
for( const std::string input : { "BUN", "bu", "daf", "pork", "udd", "COY", "" } )
{
std::cout << "input: \"" << input << "\"\n" ;
std::vector<std::string> first_names ;
std::vector<std::string> last_names ;
search_for_names( names, N, input, first_names, last_names ) ;
std::cout << '\t' << first_names.size() << " #matching first name\n" ;
if( !first_names.empty() ) for( const std::string& name : first_names ) std::cout << "\t\t" << name << '\n' ;
std::cout << '\t' << last_names.size() << " #matching last name\n" ;
if( !last_names.empty() ) for( const std::string& name : last_names ) std::cout << "\t\t" << name << '\n' ;
std::cout << "-------------\n" ;
}
}
| |