How to do case-insensitive string comparison in C++

Methods

  1. Use std::equal and std::toupper
  2. Use boost::iequals

1. Use std::equal and std::toupper

#include <string>
#include <algorithm>
#include <cstring>

struct iequal
{
    bool operator()(int c1, int c2) const
    {
        return std::toupper(c1) == std::toupper(c2);
    }
};

bool iequals(const std::string& str1, const std::string& str2)
{
    return std::equal(str1.begin(), str1.end(), str2.begin(), iequal());
}

2. Use boost::iequals

#include <boost/algorithm/string/predicate.hpp>

bool same = boost::iequals(str1, str2);

Reference: Function template iequals

Related