c语言怎样使用strcmp比较字符串大小
在C语言中,可使用strcmp()
函数来比较两个字符串的大小。strcmp()
函数会依照ASCII值逐一比较两个字符串中对应位置上的字符,直到找到区分的字符还是其中一个字符串到达结束位置。
strcmp()
函数的原型以下:
int strcmp(const char *str1, const char *str2);
其中,str1
和str2
分别为要比较的两个字符串。
strcmp()
函数返回值为整型,其含义以下:
str1
小于str2
,则返回值为负数;str1
等于str2
,则返回值为0;str1
大于str2
,则返回值为正数。下面是一个示例代码,演示了怎样使用strcmp()
函数来比较两个字符串的大小:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if (result < 0) {
printf("'%s' is less than '%s'
", str1, str2);
} else if (result > 0) {
printf("'%s' is greater than '%s'
", str1, str2);
} else {
printf("'%s' is equal to '%s'
", str1, str2);
}
return 0;
}
在上面的示例中,str1
和str2
分别为"apple"和"banana"两个字符串。通过strcmp()
函数比较后,根据返回值输出相应的结果。
TOP