温馨提示×

C语言字符串如何比较大小

小亿
121
2023-11-28 00:39:37
栏目: 编程语言

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

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

该函数将两个字符串作为参数,如果str1小于str2,则返回一个负整数;如果str1等于str2,则返回0;如果str1大于str2,则返回一个正整数。

示例代码如下:

#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",因为在字典序中,“hello"小于"world”。

0