I have two postcodes char*
that I want to compare, ignoring case.
Is there a function to do this?
Or do I have to loop through each use the tolower func
I would use stricmp()
. It compares two strings without regard to case.
Note that, in some cases, converting the string to lower case can be faster.
int strcmpInsensitive(char* a, char* b)
{
return strcmp(lowerCaseWord(a), lowerCaseWord(b));
}
char* lowerCaseWord(char* a)
{
char *b=new char[strlen(a)];
for (int i = 0; i < strlen(a); i++)
{
b[i] = tolower(a[i]);
}
return b;
}
good luck
Edit-lowerCaseWord function get a char* variable with, and return the lower case value of this char*. For example "AbCdE" for value of char*, will return "abcde".
Basically what it does is to take the two char* variables, after being transferred to lower case, and make use the strcmp function on them.
For example- if we call the strcmpInsensitive function for values of "AbCdE", and "ABCDE", it will first return both values in lower case ("abcde"), and then do strcmp function on them.
There is no function that does this in the C standard. Unix systems that comply with POSIX are required to have strcasecmp in the header strings.h
; Microsoft systems have stricmp
. To be on the portable side, write your own:
int strcicmp(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;
}
}
But note that none of these solutions will work with UTF-8 strings, only ASCII ones.
Take a look to strcasecmp() in strings.h
.
static int ignoreCaseComp (const char *str1, const char *str2, int length)
{
int k;
for (k = 0; k < length; k++)
{
if ((str1[k] | 32) != (str2[k] | 32))
break;
}
if (k != length)
return 1;
return 0;
}
Reference