strcmp函数是C语言中的字符串比较函数,用于比较两个字符串的大小。
其函数原型为:
int strcmp(const char *str1, const char *str2);
参数str1
和str2
分别为要进行比较的两个字符串。函数返回值为整型,具有以下几种情况:
- 如果
str1
等于str2
,则返回0。 - 如果
str1
小于str2
,则返回负数。 - 如果
str1
大于str2
,则返回正数。
strcmp函数按照字典顺序比较两个字符串中相应的字符,直到遇到不同的字符或者两个字符串的结尾。比较时,依次比较字符的ASCII值。
例如:
#include#include int main() { char str1[] = "hello"; char str2[] = "world"; int result = strcmp(str1, str2); if (result == 0) { printf("str1 equals to str2\n"); } else if (result < 0) { printf("str1 is less than str2\n"); } else { printf("str1 is greater than str2\n"); } return 0; }
输出结果为:
str1 is less than str2
上述例子中,“hello"和"world"两个字符串进行了比较,由于"hello"在字典顺序上小于"world”,所以返回了负数。