这个问题在这里已有答案:
创建一个函数来确定两个字符串是否相等但忽略它们的情况。到目前为止我有
bool isEqual(string str1, string str2) {
bool result = true;
for(int i = 0; I < str1.length(); i++) {
if(str1[i]==str2[i]||str1[i]==toupper(str2[i])||str1[i]==tolower(str2[i])){
//keep result==true
}
else {
result = false;
}
}
return result;
}
但这似乎是一个非常低效的方法来解决这个问题的逻辑,有人有任何建议吗?谢谢
我的建议。
std::tolower()
或std::toupper()
。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);
}
一个更简单的版本是比较开始时字符串的长度,如果长度不等,则返回false
。感谢@PeteBecker的建议。
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;
}