C++ wcscoll()

The wcscoll() function in C++ compares two null terminated string. The comparison is based on the current locale defined by the LC_COLLATE category.

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

wcscoll() prototype

int wcscoll( const wchar_t* lhs, const wchar_t* rhs );

The wcscoll() function takes two arguments: lhs and rhs. It compares the contents of lhs and rhs based on the current locale of LC_COLLATE category.


wcscoll() Parameters

  • lhs and rhs: Pointer to the null terminated wide strings to compare.

wcscoll() Return value

The wcscoll() function returns a:

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

Example: How wcscoll() function works?

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

void compare(const wchar_t* p1, const wchar_t* p2)
{
	if(wcscoll(p1, p2) < 0)
		wcout << p1 << L" precedes " << p2 << '\n';
	else if (std::wcscoll(p1, p2) > 0)
		wcout << p2 << L" precedes " << p1 << '\n';
	else
		wcout << p2 << L" equals " << p1 << '\n';
}

int main()
{
	wchar_t str1[] = L"årtist";
	wchar_t str2[] = L"äpple";
	
	setlocale(LC_ALL, "en_US.utf8");
	wcout << L"In the American locale: ";
	compare(str1, str2);

	setlocale(LC_ALL, "sv_SE.utf8");
	wcout << L"In the Swedish locale: ";
	compare(str1, str2);
	
	return 0;
}

When you run the program, the output will be:

In the American locale: äpple precedes årtist
In the Swedish locale: årtist precedes äpple
Did you find this article helpful?