Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-08-11) 阅读数 9 #程序编程
文章标签 c语言

在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”。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门