Comparing wstring with ignoring the case

39,897

Solution 1

If you don't mind being tied to Microsoft implementation you can use this function defined in <string.h>

int _wcsnicmp(
   const wchar_t *string1,
   const wchar_t *string2,
   size_t count 
);

But if you want best performance/compatibility/functionality ratio you will probably have to look at boost library (part of it is stl anyway). Simple example (taken from different answer to different question):

#include <boost/algorithm/string.hpp>

std::wstring wstr1 = L"hello, world!";
std::wstring wstr2 = L"HELLO, WORLD!";

if (boost::iequals(wstr1, wstr2))
{
    // Strings are identical
}

Solution 2

Using the standard library:

bool comparei(wstring stringA , wstring stringB)
{
    transform(stringA.begin(), stringA.end(), stringA.begin(), toupper);
    transform(stringB.begin(), stringB.end(), stringB.begin(), toupper);

    return (stringA == stringB);
}

wstring stringA = "foo";
wstring stringB = "FOO";
if(comparei(stringA , stringB))
{
    // strings match
}

Solution 3

You can use std::tolower() to convert the strings to lowercase or use the function wcscasecmp to do a case insensitive compare on the c_str()'s.

Here is a comparison functor you can use directly as well:

struct ci_less_w
{
  bool operator() (const std::wstring & s1, const std::wstring & s2) const
  {
      #ifndef _WIN32
            return wcscasecmp(s1.c_str(), s2.c_str()) < 0;
      #else
            return _wcsicmp(s1.c_str(), s2.c_str()) < 0;
      #endif
  }
};

Solution 4

Talking about English right ?! though I would go with my lovely Boost :)

bool isequal(const std::wstring& first, const std::wstring& second)
{
    if(first.size() != second.size())
        return false;

    for(std::wstring::size_type i = 0; i < first.size(); i++)
    {
        if(first[i] != second[i] && first[i] != (second[i] ^ 32))
            return false;
    }

    return true;
}

Solution 5

You could use the boost string algorithms library. Its a header only library as long as you're not going to do regex. So you can do that very easily.

http://www.boost.org/doc/libs/1_39_0/doc/html/string_algo.html

Share:
39,897
Kiran Kumar
Author by

Kiran Kumar

Software developer from Bangalore, my area of interest is mainly C++. 33rd to C++ Gold Badge

Updated on July 18, 2022

Comments

  • Kiran Kumar
    Kiran Kumar almost 2 years

    I am sure this would have been asked before but couldn't find it. Is there any built in (i.e. either using std::wstring's methods or the algorithms) way to case insensitive comparison the two wstring objects?