C語言標準庫中的 strcmp() 函數用于比較兩個字符串。
strcmp() 函數原型如下:
int strcmp (const char * str1, const char * str2);
- const char *str1 表示待比較字符串 1 的首地址;
- const char *str2 表示待比較字符串 2 的首地址。
如果兩個字符串相同,則返回 0;否則返回其他值。
下面程序展示了一個使用 strcmp() 函數比較字符串的示例:
/**
* 快速入門C語言 https://xiecoding.cn/c/
**/
#include <stdio.h>
#include <string.h>
int main()
{const char *str1 = "abcdefg";const char *str2 = "abcdefgh";const char *str3 = "abcdef";// str1 與自己進行比較int ret = strcmp(str1, str1);printf("%d\n", ret);// str1 與 str2 進行比較ret = strcmp(str1, str2);printf("%d\n", ret);// str1 與 str3 進行比較ret = strcmp(str1, str3);printf("%d\n", ret);return 0;
}
運行結果為:
0
-1
1
字符串str1與自己進行比較,結果相同,因此返回了 0。"abcedfg" 與 "abcedfgh" 進行比較,返回了 -1。"abcedfg" 與 "abcedf" 進行比較,返回了 1。
不相同的情況下,有兩種不同的結果:1 和 -1。這是為什么呢?
下圖展示了字符串比較的過程:
圖 1 字符串比較內部規則
字符串比較函數會依次比較每個字符,如果相同,則比較下一個字符;如果直到 '\0' 字符都相同,則返回 0,表示兩字符串相同;如果不相同,則比較當前字符的 ASCII 碼。
如果 str1 的當前字符大于 str2 的當前字符,則返回 1;否則返回 -1。例如當 str1 與 str2 進行比較時,不同的字符是 '\0' 與 'h',因為 '\0' 小于 'h',所以返回 -1;str1 與 str3 比較時,不同的字符是 'g' 與 '\0',因為 'g' 大于 '\0',所以返回 1。