"JKop" <NU**@NULL.NULL> wrote in message
news:8k*******************@news.indigo.ie...
Returns true if strings are identical, returns false if strings are not
identical. (without regard to case).
bool CompareWithoutRegardToCase(const char* x, const char* y)
{
//Undefined Behaviour if supplied with null pointers ;-D
if ( !*x || !*y ) //valid pointer to null string
{
if ( !*x && !*y ) return true; //2 null strings are equal.
return false;
}
do
{
if ( tolower( static_cast<unsigned char>(*x) ) == tolower(
static_cast<unsigned char>(*y) ) ) continue;
else
{
return false;
}
}
while ( (++x,++y) ,*x );
return !*y;
}
Looks good, though the loop and return statement make it look more
complicated than it really is (my version below looks simpler to me at
least). Also, I don't think the cast to unsigned char is necessary. In the
code below, I've also stored the result of *x in a variable of type char so
as to avoid additional memory lookups due to aliasing -- but I wonder how
much this improves performance. Your comments are very good too, but I left
them out to save space.
bool CompareWithoutRegardToCase(const char* xx, const char* yy) {
for ( ; ; ++xx, ++yy) {
char x = tolower(*xx);
char y = tolower(*yy);
if (x != y) return false;
if (!x && !y) return true;
}
return false; // never reached
}
Be aware that there is std::equal of 5 arguments in #include <algorithm>.
std::equal(a, a+strlen(a), b, b+strlen(b), eqnocase());
where
struct eqnocase {
bool operator()(char lhs, char rhs) const { return tolower(lhs) ==
tolower(rhs); }
};
The next exercise is to write a CompareWithoutRegardToCase that returns an
int: < 0 if lhs < rhs, 0 if lhs == rhs, >0 if lhs > rhs. Wait a sec, is
that the convention of strcmp (I always get confused and have to look it
up)? Some implementations already provide this function with the name
stricmp, but it's not part of the standard.