🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# C `strcmp()`函数 > 原文: [https://beginnersbook.com/2017/11/c-strcmp-function/](https://beginnersbook.com/2017/11/c-strcmp-function/) **`strcmp()`函数**比较两个字符串并根据结果返回一个整数值。 ## C `strcmp()`函数声明 ```c int strcmp(const char *str1, const char *str2) ``` `str1` - 第一个字符串 `str2` - 第二个字符串 ## `strcmp()`的返回值 此函数根据比较结果返回以下值: * 0:如果两个字符串相等 * `> 0`:如果字符串`str1`的第一个不匹配字符的 ASCII 值**大于**字符串`str2`中的字符 * `< 0`:如果字符串`str1`的第一个不匹配字符的 ASCII 值**小于**字符串`str2`中的字符 > 根据许多在线教程,当第一个字符串大于第二个字符串时,此函数返回正值,这绝对是**不是真的**,或者你可以说没有正确表达,因为当我们说一个字符串大于第二个字符串时我们在谈论长度。但是,此函数不比较长度,它将第一个字符串的每个字符的 ASCII 值与第二个字符串匹配,如果第一个字符串中第一个不匹配字符的 ASCII 值大于第二个字符串的不匹配字符的 ASCII 值,则返回正数。 让我们举一个例子来理解这一点。 ## 示例:C 中的`strcmp()`函数 ```c #include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[20]; int result; //Assigning the value to the string str1 strcpy(str1, "hello"); //Assigning the value to the string str2 strcpy(str2, "hEllo"); result = strcmp(str1, str2); if(result > 0) { printf("ASCII value of first unmatched character of str1 is greater than str2"); } else if(result < 0) { printf("ASCII value of first unmatched character of str1 is less than str2"); } else { printf("Both the strings str1 and str2 are equal"); } return 0; } ``` 输出: ```c ASCII value of first unmatched character of str1 is greater than str2 ``` 在上面的例子中,我们使用函数`strcmp()`比较两个字符串`str1`和`str2`。在这种情况下,`strcmp()`函数返回一个大于 0 的值,因为第一个不匹配字符`'e'`的 ASCII 值是 101,它大于`'E'`的 ASCII 值 69。 #### 相关文章: 1. [C - `strcat()`示例](https://beginnersbook.com/2017/11/c-strcat-function-with-example/) 2. [C - `strncat()`示例](https://beginnersbook.com/2017/11/c-strncat-function/) 3. [C - `strchr()`示例](https://beginnersbook.com/2017/11/c-strchr-function/)