温馨提示×

c语言字符串怎么比较大小

小亿
116
2024-01-10 13:48:31
栏目: 编程语言

在C语言中,字符串的比较可以使用strcmp函数来完成。strcmp函数的原型为:

int strcmp(const char *str1, const char *str2); 

该函数比较两个字符串str1和str2的大小,如果str1小于str2,则返回一个负整数;如果str1大于str2,则返回一个正整数;如果str1等于str2,则返回0。

以下是一个比较字符串大小的示例代码:

#include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello"; char str2[20] = "World"; int result = strcmp(str1, str2); if (result < 0) { printf("str1 is less than str2\n"); } else if (result > 0) { printf("str1 is greater than str2\n"); } else { printf("str1 is equal to str2\n"); } return 0; } 

输出结果为:

str1 is less than str2 

0