c语言strcmp的用法是什么

   2025-02-15 6720
核心提示:strcmp是C语言中的一个字符串比较函数,用于比较两个字符串是否相等。函数原型如下:int strcmp(const char *s1, const char *s2

strcmp是C语言中的一个字符串比较函数,用于比较两个字符串是否相等。

函数原型如下:

int strcmp(const char *s1, const char *s2);

参数s1和s2分别是要比较的两个字符串。

如果字符串s1和s2相等,即每个对应位置的字符都相等,则返回值为0。

如果字符串s1大于s2,则返回值大于0。

如果字符串s1小于s2,则返回值小于0。

下面是一个使用strcmp函数的示例:

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

输出结果为:

str1 is smaller than str2

这是因为字符串"Hello"在字母顺序上小于字符串"World"。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言