溫馨提示×

C語言字符串如何比較大小

小億
185
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女