strcmp
函数功能
比较两个字符串的字典顺序。它逐个字符比较两个字符串,直到发现不同的字符或者到达字符串结束符(\0)。返回结果依据比较结果,返回正负值或0。
函数定义
int strcmp(const char *str1, const char *str2);
参数说明
参数名 |
描述 |
取值范围 |
输入/输出 |
---|---|---|---|
str1 |
第一个字符串的指针。 |
非空指针,指向以\0结尾的字符串指针 |
输入 |
str2 |
第二个字符串的指针。 |
非空指针,指向以\0结尾的字符串指针 |
输入 |
返回值
- 成功:返回值为整数。
- 如果str1小于str2,返回负值。
- 如果str1等于str2,返回0。
- 如果str1大于str2,返回正值。
- 失败:对标开源Glibc,不返回特殊异常值。

比较区分字符的大小写,因此字符串“abc”和“ABC”是不同的。
示例
#include <stdio.h> #include <string.h> int main() { const char *str1 = "apple"; const char *str2 = "banana"; const char *str3 = "apple"; const char *str4 = "Banana"; const char *str5 = "APPLE"; int result1 = strcmp(str1, str2); printf("apple compared to banana: %d\n", result1); int result2 = strcmp(str1, str3); printf("apple compared to apple: %d\n", result2); int result3 = strcmp(str1, str4); printf("apple compared to Banana: %d\n", result3); int result4 = strcmp(str5, str1); printf("APPLE compared to apple: %d\n", result4); return 0; }
运行结果:
apple compared to banana: -1 apple compared to apple: 0 apple compared to Banana: 31 APPLE compared to apple: -32
父主题: 函数定义