C++ 忽略大小写时确定两个字符串相等的逻辑问题

C++ 忽略大小写时确定两个字符串相等的逻辑问题,c++,C++,生成一个确定两个字符串是否相等但忽略大小写的函数。到目前为止我有 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 r

生成一个确定两个字符串是否相等但忽略大小写的函数。到目前为止我有

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;
}
但这似乎是一个非常低效的方式来做这个问题的逻辑,有人有任何建议吗?谢谢我的建议

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;
}
使用迭代器,而不是带有索引的数组运算符。 迭代两个输入。 在比较所有字符时,对其使用std::tolower或std::toupper。 知道答案后立即返回。 一个更简单的版本是在开始时比较字符串的长度,如果长度不相等,则返回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;
}

如果您不知道编码,则无法完成。如果您确实知道编码,您将需要使用该编码来帮助完成这项工作。如果使用Unicode,请使用fold case忽略大小写。显示的代码不仅效率低下,而且是错误的,这将导致未定义的行为,或者使用不同长度的字符串产生错误的结果。首先修复代码,使其使用不同长度的字符串给出正确的结果,然后看看是否能够找出如何在if语句中只进行一次比较,这将尽可能有效。而不是result=false;返回false;。不需要在不匹配后继续检查。@PeteBecker,的确如此。谢谢你的建议。