温馨提示×

strcmp在c语言中怎么用

小亿
84
2023-12-21 11:47:16
栏目: 编程语言

strcmp函数是用来比较两个字符串的大小的函数,其原型为:

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

函数返回值为整型,表示两个字符串的大小关系。具体用法如下:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "hello";
    char str2[] = "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,表示str1str2小。如果两个字符串相等,则输出str1 is equal to str2。如果str1大于str2,则输出str1 is greater than str2

0