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


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


C++ 中的wcsncmp() 函数比较两个空终止宽字符串的指定数量的宽字符。比较是按字典顺序进行的。

wcsncmp() 函数在<cwchar> 头文件中定义。

wcsncmp()原型

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

wcsncmp() 函数有两个参数:lhs , rhscount。它按字典顺序比较lhsrhs 的内容最多为count 宽字符。

结果的符号是在 lhsrhs 中不同的第一对宽字符之间的差异符号。

如果 lhsrhs 中的任何一个不指向空终止的宽字符串,则 wcsncmp() 的行为是未定义的。

参数:

  • lhs:指向要比较的空终止宽字符串之一的指针。
  • rhs:指向要比较的空终止宽字符串之一的指针。
  • count:要比较的最大宽字符数。

返回:

wcsncmp() 函数返回:

  • 如果 lhs 中第一个不同的宽字符大于 rhs 中相应的宽字符,则为正值。
  • 如果 lhs 中第一个不同的宽字符小于 rhs 中相应的宽字符,则为负值。
  • 如果 lhs 和 rhs 的第一个 count 宽字符相等,则为 0。

示例:wcsncmp() 函数如何工作?

#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;
}

运行程序时,输出将是:

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

相关用法


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