在本教程中,我們將借助示例了解 C++ strcmp() 函數。
C++ 中的 strcmp()
函數比較兩個 null-terminating 字符串 (C-strings)。比較是按字典順序進行的。它在cstring 頭文件中定義。
示例
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char str1[] = "Megadeth";
char str2[] = "Metallica";
// compare str1 and str2 lexicographically
int result = strcmp(str1, str2);
cout << result;
return 0;
}
// Output: -1
strcmp() 語法
用法:
strcmp(const char* lhs, const char* rhs);
這裏,
lhs
代表左側rhs
代表右手邊
參數:
strcmp()
函數采用以下參數:
- lhs- 指向需要比較的C-string的指針
- rhs- 指向需要比較的C-string的指針
返回:
strcmp()
函數返回:
- a 正值如果第一個不同的字符
lhs
大於對應的字符rhs
. - a 負值如果第一個不同的字符
lhs
小於對應的字符rhs
. - 0如果
lhs
和rhs
是平等的。
strcmp() 原型
cstring 頭文件中定義的strcmp()
原型為:
int strcmp( const char* lhs, const char* rhs );
strcmp()
按字典順序比較lhs
和rhs
的內容。- 結果的符號是在
lhs
和rhs
中不同的第一對字符之間的差異符號。
strcmp() 未定義行為
的行為strcmp()
是不明確的如果:
lhs
或rhs
中的任何一個都不指向 C-strings(以空字符結尾的字符串)
示例 1:C++ strcmp()
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char str1[] = "Megadeth";
char str2[] = "Metallica";
// returns -1 because "Megadeth" < "Metallica" lexicographically
int result = strcmp(str1, str2);
cout << "Comparing " << str1 << " and " << str2 << ": " << result << endl;
// returns 1 because "Metallica" > "Megadeth" lexicographically
result = strcmp(str2, str1);
cout << "Comparing " << str2 << " and " << str1 << ": " << result << endl;
// returns 1 because "Megadeth" = "Megadeth" lexicographically
result = strcmp(str1, str1);
cout << "Comparing " << str1 << " and " << str1 << ": " << result;
return 0;
}
輸出
Comparing Megadeth and Metallica: -1 Comparing Metallica and Megadeth: 1 Comparing Megadeth and Megadeth: 0
示例 2:在用戶定義的函數中使用 strcmp()
#include <cstring>
#include <iostream>
using namespace std;
// function to display the result of strcmp()
void display(char *lhs, char *rhs) {
// compare display() parameters lhs and rhs
int result = strcmp(lhs, rhs);
if (result > 0)
cout << rhs << " precedes " << lhs << endl;
else if (result < 0)
cout << rhs << " follows " << lhs << endl;
else
cout << lhs << " and " << rhs << " are same" << endl;
}
int main() {
char str1[] = "Armstrong";
char str2[] = "Army";
// lhs = str1, rhs = str2
display(str1, str2);
// lhs = str2, rhs = str1
display(str2, str1);
// lhs = str1, rhs = str1
display(str1, str1);
// lhs = str2, rhs = str2
display(str2, str2);
return 0;
}
輸出
Army follows Armstrong Armstrong precedes Army Armstrong and Armstrong are same Army and Army are same
相關用法
- C++ strcmp()用法及代碼示例
- C++ strchr()用法及代碼示例
- C++ strcat()用法及代碼示例
- C++ strcat() vs strncat()用法及代碼示例
- C++ strcspn()用法及代碼示例
- C++ strcpy()用法及代碼示例
- C++ strcoll()用法及代碼示例
- C++ string::length()用法及代碼示例
- C++ string::npos用法及代碼示例
- C++ strncat()用法及代碼示例
- C++ strstr()用法及代碼示例
- C++ strtok()用法及代碼示例
- C++ strtod()用法及代碼示例
- C++ strtoimax()用法及代碼示例
- C++ strpbrk()用法及代碼示例
- C++ strxfrm()用法及代碼示例
- C++ strspn()用法及代碼示例
- C++ strncmp()用法及代碼示例
- C++ strtoull()用法及代碼示例
- C++ string at()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ strcmp()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。