一、strcmp函數簡介
strcmp函數是C語言中常用的字符串比較函數,用於比較兩個字符串的大小關係。該函數在C++中依然保留並繼續使用,而且其用法也比較簡單,因此,學會strcmp函數的使用對於C++程序員來說非常必要。
二、strcmp函數的語法
strcmp函數的語法如下:
int strcmp(const char* str1, const char* str2);
其中,str1和str2是要比較的字符串。
三、strcmp函數的返回值
strcmp函數的返回值是一個整數,包含以下三種情況:
- 如果str1等於str2,則返回0。
- 如果str1大於str2,則返回一個大於0的整數。
- 如果str1小於str2,則返回一個小於0的整數。
四、strcmp函數的示例
下面通過幾個簡單的示例來演示strcmp函數的使用。
示例1:比較相等的字符串
#include #include using namespace std; int main() { char str1[] = "hello"; char str2[] = "hello"; if (strcmp(str1, str2) == 0) cout << "str1 等於 str2" << endl; else cout << "str1 不等於 str2" << endl; return 0; }
運行結果:
str1 等於 str2
示例2:比較不相等的字符串
#include #include using namespace std; int main() { char str1[] = "hello"; char str2[] = "world"; if (strcmp(str1, str2) == 0) cout << "str1 等於 str2" < 0) cout << "str1 大於 str2" << endl; else cout << "str1 小於 str2" << endl; return 0; }
運行結果:
str1 小於 str2
示例3:英文排序
下面的示例展示如何使用strcmp函數對一組字符串進行英文排序。
#include #include #include using namespace std; bool cmp(const char* str1, const char* str2) { return strcmp(str1, str2) < 0; } int main() { char arr[][100] = { "banana", "orange", "apple", "pear" }; sort(arr, arr + 4, cmp); for (int i = 0; i < 4; i++) cout << arr[i] << endl; return 0; }
運行結果:
apple banana orange pear
五、總結
通過以上幾個示例,我們可以看到strcmp函數的使用非常方便,可以快速進行字符串大小關係的比較。同時,對於排序等操作,也可以通過定義cmp函數,結合strcmp函數一同使用,實現對字符串數組的排序。
原創文章,作者:TNOO,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/145018.html