search an array of strings

how would i create a function that searches a data from an array of strings?
Last edited on
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
#include <iostream>
#include <string>
#include <cctype>

// return true if the two strings are the same, ignoring case
bool eq_ncase( const std::string& a, const std::string& b )
{
    if( a.size() != b.size() ) return false ;

    for( std::size_t i = 0 ; i < a.size() ; ++i )
        if( std::toupper( a[i] ) != std::toupper( b[i] ) ) return false ;
        // pedantic: std::toupper( (unsigned char)a[i] ) etc.

    return true ;
}

// look up name, return phone number (return empty string if not found)
std::string lookup_by_name( const std::string& target_name, const std::string names[],
                            const std::string phone_numbers[], std::size_t num_entries )
{
    for( std::size_t i = 0 ; i < num_entries ; ++i )
        if( eq_ncase( target_name, names[i] ) ) return phone_numbers[i] ;

    return {} ; // not found: return empty string
}

int main()
{
    const int N = 7 ;

    const std::string dwarves[N] = { "Doc", "Grumpy", "Happy", "Sleepy", "Dopey", "Bashful", "Sneezy" };
    const std::string numbers[N] = { "111", "222222", "33333", "444444", "55555", "6666666", "777777" };

    std::string target_name ;
    while( std::cout << "enter the name to look up: " && std::cin >> target_name )
    {
        const std::string number = lookup_by_name( target_name, dwarves, numbers, N ) ;

        if( !number.empty() ) std::cout << "phone number: " << number << '\n' ;
        else std::cout << "lookup failed\n" ;
    }
}
thanks for your reply!!

im just curious: is there a way to combine function bool eq_ncase and string lookupname into one?
@gongong,
i'm just curious too. Why did you delete your initial post (and now reinstate it) and why did @JLBorges' post get reported?

In case you do it again, your starter post (currently) reads
how would i create a function that searches a data from an array of strings?

and your latest reads
thanks for your reply!!
im just curious: is there a way to combine function bool eq_ncase and string lookupname into one?
my initial post got reported too... so i dont know
Topic archived. No new replies allowed.