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