Posts Tagged ‘STL’

Case Insensitive STL Strings

January 5th, 2011

All these years of using STL strings, I never knew that one could use the std::char_traits template template parameter of std::basic_string<> to generate a case insensitive implementation of STL string. The trick is to customize the char_traits<> template overriding its  eq, lt, compare & find static functions which are implemented to perform case-insensitive operations.

struct cichartraits : public std::char_traits<char> { static bool eq(const char& _Left, const char& _Right) { return ::toupper(_Left) == ::toupper(_Right); } static bool lt(const char& _Left, const char& _Right) { return ::toupper(_Left) < ::toupper(_Right); } static int compare(const char* _First1, const char* _First2, size_t _Count) { return (::_strnicmp(_First1, _First2, _Count)); } static const char* find(const char*_First, size_t _Count, const char& _Ch) { while (_Count-- > 0 && ::toupper(!*_First) != ::toupper(_Ch)) { _First++; } return _Count >= 0 ? _First : 0; } };
typedef std::basic_string<char, cichar_traits> cistring;
cistring is now a case insensitive string. Which means operation such as these are possible without any additional effort.

cistring s("AbCdEf");
s.compare("abcdef"); // will return 0!
// a table keyed with a case insensitive string!
std::map<cistring, Employee> emptable;

Until now I used to declare such containers using a custom less functor  passed as the template template parameter to the container classes.

Goes to show how you keep discovering new things in C++ even after many years of using it.