当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ wcsncmp()用法及代码示例


C /C++中的wcsncmp()函数比较两个宽字符串的字符。比较是按字典顺序进行的。此函数采用三个参数lhs,rhs和count。它按字典顺序比较了lhs和rhs的内容,最多可计数宽字符。

注意:如果lhs或rhs都不指向以null终止的宽字符串,则wcsncmp()的行为是不确定的。

用法:


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

参数:该函数接受三个强制性参数,如下所述:

  • lhs : 要比较的字符串
  • rhs : 要比较的字符串
  • count : 要比较的最大字符数

返回值:该函数返回三个值,如下所示:

  • 正值:如果lhs中的第一个不同字符大于rhs中的相应字符。
  • 负值:如果lhs中的第一个不同字符小于rhs中的相应字符。
  • 零:如果两个字符串中比较的字符形成相同的字符串。

以下示例程序旨在说明上述函数:
示例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; 
}
输出:
First 4 characters of  are same
geekGgeek precedes geekforgeeks

示例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; 
}
输出:
First 5 characters of  are same
First 8 characters of  are same


相关用法


注:本文由纯净天空筛选整理自AmanSrivastava1大神的英文原创作品 wcsncmp() function in C/C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。