In this article, we will discuss the wcscoll function in C++ with its syntax and example.
The C++ wcscoll function compares two strings that are null-terminated. A comparison is made based on the current locale that is specified by the LC_COLLATE category.
This function compares the initial character of every string. Until the characters diverge or a null wide character that indicates the end of a string is encountered, they are regarded as equal.
Syntax:
It has the following syntax:
int wcscoll( const wchar_t* wcs1, const wchar_t* wcs2 )
Two required parameters are accepted by the function and are explained as follows:
wcs1: It is a pointer to the wide strings with null terminations that need to be compared.
wcs2: The null terminated wide strings to compare are pointed to by this pointer.
Value returned: The function yields the following three values:
- 0 , if the values show that the two strings are identical.
- Positive value: If the first character in WCS1 that differs from WCS2 is more than that character's equivalent.
- Negative Value: If the first character in WCS1 that differs from WCS2 is smaller than the corresponding character in WCS2, the value is negative.
Example 1:
Let's take an example to illustrate the use of wcscoll function in C++:
#include <iostream>
#include <clocale>
#include <cwchar>
void CompareWords(const wchar_t* word1, const wchar_t* word2)
{
if (wcscoll(word1, word2) < 0)
wcout << word1 << L" precedes " << word2 << '\n';
else if (wcscoll(word1, word2) > 0)
wcout << word2 << L" precedes " << word1 << '\n';
else
wcout << word1 << L" equals " << word2 << '\n';
}
int main()
{
// Initializing two words
wchar_t wordA[] = L"apple";
wchar_t wordB[] = L"banana";
// Setting American locale
setlocale(LC_ALL, "en_US.utf8");
wcout << L"In American English: ";
CompareWords(wordA, wordB);
// Setting Swedish locale
setlocale(LC_ALL, "sv_SE.utf8");
wcout << L"In Swedish: ";
CompareWords(wordA, wordB);
return 0;
}
Output:
In American English: apple precedes banana
In Swedish: apple precedes banana
Example 2:
Let's take another example to illustrate the use of wcscoll function in C++:
#include <iostream>
#include <clocale>
#include <cwchar>
void CompareWords(const wchar_t* word1, const wchar_t* word2)
{
if (wcscoll(word1, word2) < 0)
wcout << word1 << L" precedes " << word2 << '\n';
else if (wcscoll(word1, word2) > 0)
wcout << word2 << L" precedes " << word1 << '\n';
else
wcout << word1 << L" equals " << word2 << '\n';
}
int main()
{
// Initializing two words
wchar_t wordJavacpptutorial[] = L"javacpptutorial";
wchar_t wordJTP[] = L"JTP";
// Setting Czech locale
setlocale(LC_COLLATE, "cs_CZ.utf8");
wcout << L"In Czech: ";
CompareWords(wordJavacpptutorial, wordJTP);
// Setting American English locale
setlocale(LC_COLLATE, "en_US.utf8");
wcout << L"In American English: ";
CompareWords(wordJavacpptutorial, wordJTP);
return 0;
}
Output:
In Czech: javacpptutorial precedes JTP
In American English: javacpptutorial precedes JTP