比较字母但不比较strcmp

问题描述 投票:0回答:1

我想用函数 int Compare(char* A, char*B) 比较两个字符串,当 A 较大时返回 1,当 B 较大时返回 0。

假设最大字符是100,我希望顺序是‘A’< ‘a’ < ‘B’ < ‘b’ < … < ‘Z’ < ‘z’.

我不使用 strcmp 的原因是 strcmp 会给出“A”< ‘B’ < … ‘a’ < ‘b’ < … < ‘z’. Is there a way to do it with the function?

function int compare(char* A, char* B){
//compare
}

(这是一个C程序)

对于 strcmp,它给出“C”< ‘a’ as it follows the ASCII code, but I want ‘A’< ‘a’ < ‘B’ < ‘b’ < … < ‘Z’ < ‘z’

c data-structures
1个回答
0
投票

如果我们开始实现

strcmp
,它可能看起来像这样:

// returns a negative value if A < B
// returns a positive value if A > B
// returns 0 if they are equal
int compare(const char *A, const char *B) {
    for (; *A && *B; ++A, ++B) {
        if (*A != *B) return *A - *B;  // case sensitive
    }
    // if they are of equal length and reach here both *A and *B
    // will be `\0`, otherwise the longest string will be considered
    // greater than the shortest:
    return *A - *B;
}

然后,您可以在区分大小写检查之前添加不区分大小写的检查:

#include <ctype.h>

int compare(const char *A, const char *B) {
    for (; *A && *B; ++A, ++B) {
        if (isalpha(*A) && isalpha(*B)) {
            int ua = toupper((unsigned char)*A);
            int ub = toupper((unsigned char)*B);

            if (ua != ub) return ua - ub;  // case insensitive
        }
        if (*A != *B) return *A - *B;  // case sensitive
    }
    return *A - *B;
}
© www.soinside.com 2019 - 2024. All rights reserved.