Reputation: 1080
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
Upvotes: 0
Views: 218
Reputation: 3790
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]);
}
Upvotes: 1
Reputation: 145297
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;
}
}
}
Upvotes: 2