C++ wcsncmp()

The wcsncmp() function in C++ compares a specified number of wide characters of two null terminating wide strings. The comparison is done lexicographically.

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

wcsncmp() prototype

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

The wcsncmp() function takes two arguments: lhs, rhs and count. It compares the contents of lhs and rhs lexicographically upto a maximum of count wide characters.

The sign of the result is the sign of difference between the first pairs of wide characters that differ in lhs and rhs.

The behaviour of wcsncmp() is undefined if either of lhs or rhs do not point to null terminated wide strings.


wcsncmp() Parameters

  • lhs: Pointer to one of the null terminated wide strings to compare.
  • rhs: Pointer to one of the null terminated wide strings to compare.
  • count: Maximum number of wide characters to compare.

wcsncmp() Return value

The wcsncmp() function returns a:

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

Example: How wcsncmp() function works?

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

void compare(wchar_t *lhs, wchar_t *rhs, int count)
{
	int result;
	result = wcsncmp(lhs, rhs, count);

	if(result > 0)
		wcout << rhs << " precedes " << lhs << endl;
	else if (result < 0)
		wcout << lhs << " 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 str1[] = L"\u0166\u0113\u010b\u0127\u0149\u0151\u013c\u014c\u0123\u0194";
	wchar_t str2[] = L"Ŧēċħnology";
	
	compare(str1,str2,4);
	compare(str1,str2,7);
	
	return 0;
}

When you run the program, the output will be:

First 4 characters of ŦēċħʼnőļŌģƔ and Ŧēċħnology are same
Ŧēċħnology precedes ŦēċħʼnőļŌģƔ