c - 如何编写正确的 strcmp?

标签 c

下面是我为 strcmp 编写的代码,我希望它不区分大写和小写字母,但它仍然区分,我该如何解决?

int strcmp(char str1[], char str2[]) {
    int i = 0;
    for (; str1[i] || str2[i];) {
        if (str1[i] > str2[i]) {
            int j = (str1[i] - str2[i]);
            if (j == 32)
                i++;
            else {
                return +1;
            }
        } else
        if (str1[i] < str2[i]) {
            int q = (str1[i] - str2[i]);
            if (q == -32) {
                i++;
            } else {
                return -1;
            }
        } else
        if (str1[i] == str2[i]) {
            i++;
        }
    }
    return 0;
}

例子: 输入:

Aryan
Semi
Kim
kim
Nap

输出:

Aryan
Kim
Nap
Semi
kim

最佳答案

你的函数有多个问题:

  • 不要名字是strcmp() .您不应该重新定义具有不同语义的标准函数。 strcmp()通常是高度优化的,您的版本可能甚至不是您通过 strcmp 时使用的版本到你的排序函数。

  • 算法不正确:相隔 32 个位置的任何 2 个字符都被视为相等,例如“0”==“P”。

  • 比较是不可传递的:你有 "A" < "_""_" < "a""A" == "a" ,这对于排序来说是非常有问题的。

  • 您不应假定 ASCII 并对大小写偏移进行硬编码。使用 toupper()来自 <ctype.h>并类型转换char值为 (unsigned char)以避免对负值的未定义行为。

  • i应该是 size_t .

  • str1str2应该是 const合格。

这是一个改进的版本:

#include <ctype.h>

int strcmp_case(const char *str1, const char *str2) {
    for (size_t i = 0;; i++) {
        int c1 = toupper((unsigned char)str1[i]);
        int c2 = toupper((unsigned char)str2[i]);
        if (c1 != c2) {
            return (c1 > c2) - (c1 < c2);
        }
        if (c1 == '\0') {
            return 0;
        }
    }
}

关于c - 如何编写正确的 strcmp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41101439/

相关文章:

c - 在 C 中获取 sleep() 中剩余的时间

c - 为什么我在比较线性搜索和二分搜索时每次都得到零?

c - 相当简单的 C 代码中的安全漏洞

c++ - 客户端中断时如何通知服务器?

c - 是否有更优化的方法来处理其中一些功能?

c++ - array[n] 和 array[] 的区别?

c - 如何使用库内的结构?

c - C 函数的一个参数丢失

c++ - 我可以定义一个结构,其对象将始终位于单独的缓存行中吗

pthread 中的条件变量和实时优先级