C++ strcoll()

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

strcmp() is enough for most string comparisons, but when dealing with unicode characters, sometimes there are certain nuances that make byte-to-byte string comparison incorrect.

For instance, if you are comparing two strings in Spanish language, they can contain accentuated characters like á, é, í, ó, ú, ü, ñ, ¿, ¡ etc.

By default, such accentuated characters come after the whole alphabet of a,b,c...z. Such comparison would be faulty because the different accents of a should actually come before b.

strcoll() uses the current locale to perform the comparison giving a more accurate result in such cases.

It is defined in <cstring> header file.

strcoll() prototype

int strcoll( const char* lhs, const char* rhs );

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

strcoll() Parameters

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

strcoll() Return value

The strcoll() 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 strcoll() function works?

#include <cstring>
#include <iostream>
using namespace std;

int main()
	char lhs[] = "Armstrong";
	char rhs[] = "Army";
	int result;
	result = strcoll(lhs,rhs);

	cout << "In the current locale ";
	if(result > 0)
		cout << rhs << " precedes " << lhs << endl;
	else if (result < 0)
		cout << lhs << " precedes " << rhs << endl;
		cout << lhs << " and " << rhs << " are same" << endl;
	return 0;

When you run the program, the output will be:

In the current locale Armstrong precedes Army