My suggestion.
- Use iterators instead of the array operator with an index.
- Iterate on both the inputs.
- Use
std::tolower()
or std::toupper()
on all characters when comparing them.
- Return immediately when you know the answer.
bool isEqual(string str1, string str2)
{
auto iter1 = begin(str1);
auto end1 = end(str1);
auto iter2 = begin(str2);
auto end2 = end(str2);
for ( ; iter1 != end1 && iter2 != end2; ++iter1, ++iter2 )
{
// This will also work.
// if ( std::tolower(*iter1) != std::tolower(*iter2) )
if ( std::toupper(*iter1) != std::toupper(*iter2) )
{
return false;
}
}
// We come here only if we have compared all the characters
// of at least one of the strings.
// The two strings are equal only if we have compared all the
// characters of BOTH the strings.
return (iter1 == end1 && iter2 == end2);
}
A simpler version would be to compare the lengths of the strings at the start and return false
if they are of unequal lengths. Thanks are due to @PeteBecker for the suggestion.
bool isEqual(string str1, string str2)
{
if ( str1.length() != str2.length() )
{
return false;
}
auto iter1 = begin(str1);
auto end1 = end(str1);
auto iter2 = begin(str2);
auto end2 = end(str2);
for ( ; iter1 != end1 && iter2 != end2; ++iter1, ++iter2 )
{
// This will also work.
// if ( std::tolower(*iter1) != std::tolower(*iter2) )
if ( std::toupper(*iter1) != std::toupper(*iter2) )
{
return false;
}
}
// We come here only if we have compared all the characters
// of BOTH the strings. In that case the strings are equal.
return true;
}