c++ - 这个字符串比较逻辑有什么缺陷?

标签 c++ string algorithm

以下

#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++))

同时增加指针 s1s2 只要 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"

因为如果字符串相等,则 s1s2 都将在 while 循环后成为空字符。

我哪里错了?

最佳答案

缺陷在于 ++ 甚至在最后一个字符不匹配时也在循环中完成。如果以下字符匹配(在本例中为 null 终止符),则它们比较为真。

关于c++ - 这个字符串比较逻辑有什么缺陷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29898434/

相关文章:

algorithm - 如何绘制精确召回图?

android - 具有种子作用的随机数生成非确定性

java - 返回两个数字的索引,以便它们加起来达到特定目标

python - 什么是从 python 字符串中删除空行的快速单行代码?

c# - 枚举值字典作为字符串

c - 递归反转 C 中的字符串?

c++ - 具有void参数回调的模板化可选参数构造函数

c++ - 在双向链表中使用指针交换节点

c++ - 强制两个线程直接访问内存中的全局变量?

c++ - 在 unicode 和非 unicode 环境中转换 TCHAR * -> std::wstring