c++stringcomparisoniostring-comparison

Best way to compare std::strings


What is the best way to compare std::strings? The obvious way would be with if/else:

std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?


Solution

  • Here's an example using std::map.

    #include <map>
    #include <string>
    #include <iostream>
    #include <utility>
    
    void first()
    {
      std::cout << "first\n";
    }
    
    void second()
    {
      std::cout << "second\n";
    }
    
    void third()
    {
      std::cout << "third\n";
    }
    
    
    int main()
    {
      typedef void(*StringFunc)();
      std::map<std::string, StringFunc> stringToFuncMap;
    
      stringToFuncMap.insert(std::make_pair("blah", &first));
      stringToFuncMap.insert(std::make_pair("blahblah", &second));
      stringToFuncMap.insert(std::make_pair("blahblahblah", &third));
    
      stringToFuncMap["blahblah"]();
      stringToFuncMap["blahblahblah"]();
      stringToFuncMap["blah"]();
    }
    

    Output is:

    second
    third
    first
    

    The benefits of this approach are:

    Look into using boost::function to make the syntax a bit nicer, especially with class member functions.