The wcscmp
function in C lexicographically compares two wide strings. The function sequentially compares the elements of both strings until it encounters a mismatch.
The process is illustrated below:
Note: A wide string is comprised of characters from the Unicode character set.
To use the wcscmp
function, you will need to include the <wchar.h>
library in the program, as shown below:
#include <wchar.h>
The prototype of the wcscmp
function is shown below:
int wcscmp(const wchar_t *s1, const wchar_t *s2);
The wcscmp
function takes two null-terminated wide strings as parameters.
The wcscmp
function compares the provided strings and returns one of the following:
s1
is lexicographically greater than s2
.s1
is lexicographically less than s2
.The behavior of the wcscmp
function is undefined if either s1
or s2
do not point to null-terminated wide strings.
The code below shows how the wcscmp
function works in C:
#include <stdio.h>#include <wchar.h>int main() {// initializing stringswchar_t str[] = L"Case";wchar_t arr[3][5] = {L"Case", L"Cave", L"Care"};// iterating over stringsfor(int i = 0; i < 3; i++){// comparing stringsint result = wcscmp(str, arr[i]);// displaying resultif(result == 0){printf("\'%ls\' and \'%ls\' are equal.\n", str, arr[i]);}else if(result < 0){printf("\'%ls\' is less than \'%ls\'.\n", str, arr[i]);}else{printf("\'%ls\' is greater than \'%ls\'.\n", str, arr[i]);}}return 0;}
First, the code initializes a 2D-Array of wide strings. Each of the strings in this array is meant to be compared with the wide string str
. The ‘L’ identifier in lines 7 and 8
informs the compiler that the Unicode character set is being used.
The for-loop
in line 11
iterates over each element in the array. The wcscmp
function in line 14
proceeds to compare the wide string stored in str
with the extracted array element, and the result is printed accordingly.
The first comparison involves the same string, “Case,” being served as both parameters to the wcscmp
function. Therefore, the result of this comparison is .
During the second iteration of the loop, a comparison occurs between the strings “Case” and “Cave.” There is a mismatch at the third character of both of these strings, and since ‘s’ appears before ‘v’ in the alphabet, wcscmp
returns a negative integer.
Similarly, in the final comparison between “Case” and “Care,” the mismatch again occurs at the third character. However, since ‘s’ appears after ‘r’ in the alphabet, a positive integer is returned by wcscmp
.