strcmp()
函数逐个字符比较两个字符串。如果字符串相等,则函数返回 0。
C strcmp() 原型
strcmp()
的函数原型是
int strcmp (const char* str1, const char* str2);
strcmp() 参数
该函数接受两个参数
- str1 - 一个字符串
- str2 - 一个字符串
strcmp() 的返回值
返回值 | 备注 |
---|---|
0 | 如果字符串相等 |
>0 | 如果 str1 中的第一个不匹配字符(ASCII码)大于 str2 中的相应字符。 |
<0 | 如果 str1 中的第一个不匹配字符(ASCII码)小于 str2 中的相应字符。 |
strcmp()
函数定义在 string.h
头文件中。
示例:C strcmp() 函数
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
输出
strcmp(str1, str2) = 32 strcmp(str1, str3) = 0
在此程序中,
- 字符串
str1
和str2
不相等。因此,结果是一个非零整数。 - 字符串
str1
和str3
相等。因此,结果是 0。