简体   繁体   中英

How do I write a proper strcmp?

Below is the code I've written for strcmp , I want it to not differentiate between uppercase and lowercase letters, However it still does, How do I fix this?

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;
}

Example: Input:

Aryan
Semi
Kim
kim
Nap

Output:

Aryan
Kim
Nap
Semi
kim

For example:

int strcasecmp(const char *a, const char *b)
{
    size_t i;
    for (i = 0; tolower((unsigned char)a[i]) == tolower((unsigned char)b[i]) && a[i]; ++i);
    return tolower((unsigned char)a[i]) - tolower((unsigned char)b[i]);
}

There are multiple problems with your function:

  • do not name is strcmp() . You should not redefine standard functions with different semantics. strcmp() is usually highly optimized, it is possible that your version is not even the one used when you pass strcmp to your sorting function.

  • The algorithm is incorrect: any 2 characters 32 positions apart are considered equal, for example "0" == "P".

  • The comparison is non transitive: you have "A" < "_" and "_" < "a" yet "A" == "a" , which is very problematic for sorting.

  • You should not assume ASCII and hard code the case offsets. Use toupper() from <ctype.h> and cast char values as (unsigned char) to avoid undefined behavior on negative values.

  • i should be a size_t .

  • str1 and str2 should be const qualified.

Here is an improved version:

#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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM