以下
#include <iostream>
unsigned short int stringCompare ( char * s1, char * s2 )
{
// returns 1 if the character arrays s1 and s2 are equal;
// returns 0 otherwise
while (*s1 && (*s1++ == *s2++));
return (!(*s1) && !(*s2));
}
int main ()
{
char str1 [] = "americano";
char str2 [] = "americana";
std::cout << stringCompare(str1,str2);
return 0;
}
打印 1
,这意味着我的函数逻辑不正确。我想明白为什么。让我解释一下我的逻辑:
while (*s1 && (*s1++ == *s2++))
同时增加指针 s1
和 s2
只要 s1 不等于 '\0'
和值 s1
指向的值与 s2
指向的值相同。它应该是一种更短的写作方式
while (*s1 && *s2)
{
if (*s1 != *s2) break;
++s1; ++s2;
}
并依靠奇特的运算符优先级来缩短它。
声明
return (!(*s1) && !(*s2))
表示
"If s1 and s2 are both the null character, return true; otherwise return false"
因为如果字符串相等,则 s1
和 s2
都将在 while
循环后成为空字符。
我哪里错了?
最佳答案
缺陷在于 ++
甚至在最后一个字符不匹配时也在循环中完成。如果以下字符匹配(在本例中为 null 终止符),则它们比较为真。
关于c++ - 这个字符串比较逻辑有什么缺陷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29898434/