I want to compare to string pointers while ignoring their case. I cant think of any C function that can do that.
For example:
ToMMy == tommy == TOMMY == tOMmy etc.....
Does anyone know how this can be done in C?
I want to compare to string pointers while ignoring their case. I cant think of any C function that can do that.
For example:
ToMMy == tommy == TOMMY == tOMmy etc.....
Does anyone know how this can be done in C?
strcasecmp()
is not a standard C function, but it is on most compilers.
Write your own:
int strnocasecmp(char const *a, char const *b)
{
for (;; a++, b++) {
int d = tolower((unsigned char)*a) - tolower((unsigned char)*b);
if (d != 0 || !*a)
return d;
}
}
Don't forget the #include <ctype.h>
library for tolower()
.
If it is OK to support only single-byte English alphabets to ignore cases, just convert each characters to lower case (or upper case) and compare.
#include <ctype.h>
int cmp(const char *a, const char *b) {
while (*a || *b) {
int c1 = tolower((unsigned char)*a++);
int c2 = tolower((unsigned char)*b++);
if (c1 != c2) return c1 > c2 ? 1 : -1;
}
return 0;
}
If you have access to strcasecmp
(POSIX) in string.h
, that's probably your best bet.
strcasecmp("TOMMY", "tOMmy") == 0
Otherwise, it's not too hard to make your own.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
bool check_strings(const char* str1, const char* str2)
{
if (strlen(str1) != strlen(str2))
return false;
do {
if (tolower(*str1++) != tolower(*str2++))
return false;
} while(*str1 || *str2)
return true;
}