Comparsion strcmp() strncmp() strcasecmp() strncasecmp()

strcase*函式不是標準 C,而是 POSIX 擴充套件。

strcmp 函式按字典順序比較兩個以 null 結尾的字元陣列。如果第一個引數在字典順序中出現在第二個引數之前,則函式返回負值,如果它們比較相等則返回零,如果第一個引數在字典順序中出現在第二個引數之後,則返回正數。

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

void compare(char const *lhs, char const *rhs)
{
    int result = strcmp(lhs, rhs); // compute comparison once
    if (result < 0) {
        printf("%s comes before %s\n", lhs, rhs);
    } else if (result == 0) {
        printf("%s equals %s\n", lhs, rhs);
    } else { // last case: result > 0
        printf("%s comes after %s\n", lhs, rhs);
    }
}

int main(void)
{
    compare("BBB", "BBB");
    compare("BBB", "CCCCC");
    compare("BBB", "AAAAAA");
    return 0;
}

輸出:

BBB equals BBB
BBB comes before CCCCC
BBB comes after AAAAAA

作為 strcmpstrcasecmp 函式在將每個字元轉換為小寫字母后,也會按字典順序對其引數進行比較:

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

void compare(char const *lhs, char const *rhs)
{
    int result = strcasecmp(lhs, rhs); // compute case-insensitive comparison once
    if (result < 0) {
        printf("%s comes before %s\n", lhs, rhs);
    } else if (result == 0) {
        printf("%s equals %s\n", lhs, rhs);
    } else { // last case: result > 0
        printf("%s comes after %s\n", lhs, rhs);
    }
}

int main(void)
{
    compare("BBB", "bBB");
    compare("BBB", "ccCCC");
    compare("BBB", "aaaaaa");
    return 0;
}

輸出:

BBB equals bBB
BBB comes before ccCCC
BBB comes after aaaaaa

strncmpstrncasecmp 最多比較 n 個字元:

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

void compare(char const *lhs, char const *rhs, int n)
{
    int result = strncmp(lhs, rhs, n); // compute comparison once
    if (result < 0) {
        printf("%s comes before %s\n", lhs, rhs);
    } else if (result == 0) {
        printf("%s equals %s\n", lhs, rhs);
    } else { // last case: result > 0
        printf("%s comes after %s\n", lhs, rhs);
    }
}

int main(void)
{
    compare("BBB", "Bb", 1);
    compare("BBB", "Bb", 2);
    compare("BBB", "Bb", 3);
    return 0;
}

輸出:

BBB equals Bb
BBB comes before Bb
BBB comes before Bb