C++中的memcmp()函數比較兩個指針對象的指定字符數
memcmp()原型
int memcmp( const void* lhs, const void* rhs, size_t count );
memcmp()
函數采用三個參數:lhs
, rhs
和 count
。此函數首先將 lhs
和 rhs
指向的對象解釋為 unsigned char
的數組。然後它按字典順序比較lhs
和rhs
的前count
字符。
它在<cstring> 頭文件中定義。
參數:
lhs and rhs
:指向要比較的內存對象的指針。count
:要比較的最大字節數。
返回:
memcmp() 函數返回:
- 如果
lhs
中的第一個不同字節大於rhs
中的相應字節,則為正值。 - 如果
lhs
中的第一個不同字節小於rhs
中的相應字節,則為負值。 - 如果
lhs
和rhs
的第一個計數字節相等,則為 0。
示例:memcmp() 函數的工作原理
#include <cstring>
#include <iostream>
using namespace std;
void display(char *lhs, char *rhs, int result, int count)
{
if(result > 0)
cout << rhs << " precedes " << lhs << endl;
else if (result < 0)
cout << lhs << " precedes " << rhs << endl;
else
cout << "First " << count << " characters of " << lhs << " and " << rhs << " are same" << endl;
}
int main()
{
char lhs[] = "Hello World!";
char rhs[] = "Hello Earth!";
int result;
result = memcmp(lhs, rhs, 5);
display(lhs, rhs, result, 5);
result = memcmp(lhs, rhs, 7);
display(lhs, rhs, result, 7);
return 0;
}
運行程序時,輸出將是:
First 5 characters of Hello World! and Hello Earth! are same Hello Earth! precedes Hello World!
相關用法
- C++ memchr()用法及代碼示例
- C++ memcpy()用法及代碼示例
- C++ memset()用法及代碼示例
- C++ memmove()用法及代碼示例
- C++ merge()用法及代碼示例
- C++ map lower_bound()用法及代碼示例
- C++ multimap key_comp()用法及代碼示例
- C++ multimap empty()用法及代碼示例
- C++ multimap cend()用法及代碼示例
- C++ multiset begin()、end()用法及代碼示例
- C++ mbtowc()用法及代碼示例
- C++ map::at()用法及代碼示例
- C++ multiset value_comp()用法及代碼示例
- C++ multimap insert()用法及代碼示例
- C++ map max_size()用法及代碼示例
- C++ multiset emplace()用法及代碼示例
- C++ multiset lower_bound()用法及代碼示例
- C++ multimap lower_bound()用法及代碼示例
- C++ multiset crbegin()、crend()用法及代碼示例
- C++ multimap rend()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ memcmp()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。