Open In App

wcsncmp() function in C/C++

The wcsncmp() function in C/C++ compare characters of two wide strings. The comparison is done lexicographically. This function takes three arguments lhs, rhs and count. It compares the contents of lhs and rhs lexicographically upto a maximum of count wide characters.

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



Syntax:

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

Parameter :The function accepts three mandatory parameters which are described below:



Return value: The function returns three value as below:

Below programs illustrate the above function:
Program 1 :




// C++ program to illustrate the
// wcsncmp() function
#include <bits/stdc++.h>
using namespace std;
  
// function to compare two strings
void check(wchar_t* lhs, wchar_t* rhs, int count)
{
    int result;
    // compare lhs and rhs by wcsncmp
    result = wcsncmp(lhs, rhs, count);
  
    // print, as per result
    if (result < 0)
        wcout << lhs << " precedes " << rhs << "\n";
    else if (result > 0)
        wcout << rhs << " precedes " << lhs << "\n";
    else
        wcout << L"First " << count << L" characters of "
              << L" are same"
              << "\n";
}
  
// Driver code
int main()
{
    // initialize two strings lhs and rhs to compare
    wchar_t lhs[] = L"geekforgeeks";
    wchar_t rhs[] = L"geekGgeek";
  
    // check till 4th characters and till 7th characters
    check(lhs, rhs, 4);
    check(lhs, rhs, 7);
  
    return 0;
}

Output:
First 4 characters of  are same
geekGgeek precedes geekforgeeks

Program 2 :




// C++ program to illustrate the
// wcsncmp() function
#include <bits/stdc++.h>
using namespace std;
  
// function to compare two strings
void check(wchar_t* lhs, wchar_t* rhs, int count)
{
    int result;
    // compare lhs and rhs by wcsncmp
    result = wcsncmp(lhs, rhs, count);
  
    // print, as per result
    if (result < 0)
        wcout << lhs << " precedes " << rhs << "\n";
    else if (result > 0)
        wcout << rhs << " precedes " << lhs << "\n";
    else
        wcout << L"First " << count << L" characters of "
              << L" are same"
              << "\n";
}
  
// Driver code
int main()
{
    // initialize two strings lhs and rhs to compare
    wchar_t lhs[] = L"01234GFG";
    wchar_t rhs[] = L"01234GFG";
  
    // check till 5th character
    // and again till 8th character
    check(lhs, rhs, 5);
    check(lhs, rhs, 8);
  
    return 0;
}

Output:
First 5 characters of  are same
First 8 characters of  are same

Article Tags :