🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# C `strncmp()`函数 > 原文: [https://beginnersbook.com/2017/11/c-strncmp-function/](https://beginnersbook.com/2017/11/c-strncmp-function/) 在上一个教程中,我们讨论了[`strcmp()`函数](https://beginnersbook.com/2017/11/c-strcmp-function/),它用于比较两个字符串。在本指南中,我们将讨论 **`strncmp()`函数**,它与`strcmp()`相同,但`strncmp()`比较仅限于函数调用期间指定的字符数。例如,`strncmp(str1, str2, 4)`仅比较字符串`str1`和`str2`的前四个字符。 ## C `strncmp()`函数声明 ```c int strncmp(const char *str1, const char *str2, size_t n) ``` `str1` - 第一个字符串 `str2` - 第二个字符串 `n` - 需要比较的字符数。 ## `strncmp()`的返回值 此函数仅比较字符串的前`n`个(指定数量)字符,并根据比较返回以下值。 * `0`,如果字符串`str1`和`str2`都相等 * `> 0`,如果`str1`的第一个不匹配字符的 ASCII 值大于`str2` * `< 0`,如果`str1`的第一个不匹配字符的 ASCII 值小于`str2` ## 例 1:C 中的`strncmp()`函数 ```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 WORLD"); //This will compare the first 3 characters result = strncmp(str1, str2, 3); 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 Both the strings str1 and str2 are equal ``` ## `strncmp()`函数的示例 2 让我们稍微改变上面的例子。这里我们比较字符串的前四个字符。 ```c #include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[20]; int result; strcpy(str1, "hello"); strcpy(str2, "helLO WORLD"); //This will compare the first 4 characters result = strncmp(str1, str2, 4); 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 ```