在上一个教程中,我们讨论了strcmp()函数,它用于比较两个字符串。在本指南中,我们将讨论 strncmp()函数,它与strcmp()相同,但strncmp()比较仅限于函数调用期间指定的字符数。例如,strncmp(str1, str2, 4)仅比较字符串str1和str2的前四个字符。
C strncmp()函数声明
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()函数
#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;
}
输出:
Both the strings str1 and str2 are equal
strncmp()函数的示例 2
让我们稍微改变上面的例子。这里我们比较字符串的前四个字符。
#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;
}
输出:
ASCII value of first unmatched character of str1 is greater than str2
极客教程