C++ wmemcmp()

The wmemcmp() function in C++ compares a specified number of wide characters of two wide strings.

The wmemcmp() function is defined in <cwchar> header file.

wmemcmp() prototype

int wmemcmp( const wchar_t* lhs, const wchar_t* rhs, size_t count );

The wmemcmp() function takes three arguments: lhs, rhs and count. This function compares the first count wide characters of lhs and rhs lexicographically.


wmemcmp() Parameters

  • lhs and rhs: Pointer to the wide character array to compare.
  • count: Maximum numbers of wide characters to compare.

wmemcmp() Return value

The wmemcmp() function returns a:

  • positive value if the first differing wide character in lhs is greater than the corresponding byte in rhs.
  • negative value if the first differing wide character in lhs is less than the corresponding byte in rhs.
  • 0 if the first count wide characters of lhs and rhs are equal

Example: How wmemcmp() function works?

#include <cwchar>
#include <clocale>
#include <iostream>
using namespace std;

void compare(wchar_t *lhs, wchar_t *rhs, int count)
{
	int result = wmemcmp(lhs, rhs, count);
	
	if(result > 0)
		wcout << rhs << L" precedes " << lhs << endl;
	else if (result < 0)
		wcout << lhs << L" precedes " << rhs << endl;
	else
		wcout << L"First " << count << L" characters of " << lhs << L" and " << rhs << L" are same" << endl;
}

int main()
{
	setlocale(LC_ALL, "en_US.utf8");

	wchar_t lhs[] = L"\u0386\u03a6\u03aa\u03ac\u03c8\u03c9\u03ee";
	wchar_t rhs[] = L"\u0386\u03a6\u03aa\u03ac\u03c0\u03c7\u03fb";
	
	compare(lhs, rhs, 4);
	compare(lhs, rhs, 7);
	
	return 0;
}

When you run the program, the output will be:

First 4 characters of ΆΦΪάψωϮ and ΆΦΪάπχϻ are same
ΆΦΪάπχϻ precedes ΆΦΪάψωϮ