在忽略案例[重复]的情况下确定两个字符串相等的逻辑问题

问题描述 投票:-3回答:1

这个问题在这里已有答案:

创建一个函数来确定两个字符串是否相等但忽略它们的情况。到目前为止我有

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;
}

但这似乎是一个非常低效的方法来解决这个问题的逻辑,有人有任何建议吗?谢谢

c++
1个回答
0
投票

我的建议。

  1. 使用迭代器而不是带索引的数组运算符。
  2. 迭代两个输入。
  3. 在比较它们时,对所有字符使用std::tolower()std::toupper()
  4. 当你知道答案时立即返回。

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.