#include <iostream>
using namespace std;
bool isEqual(const char *a,const char *b)
{
int lengthA=strlen(a);
int lengthB=strlen(b);
if( lengthA != lengthB)
{
return false;
}
int intLength=sizeof(int);
int *ptrA;
int *ptrB;
int i=0;
for(;i<lengthA/intLength;i++)
{
ptrA=(int*)(a+(i*intLength));
ptrB=(int*)(b+(i*intLength));
if(( (*ptrA) ^ (*ptrB) ))
{
return false;
}
}
i=lengthA-lengthA%intLength+1;
for(;i<lengthA;i++)
{
if(a[i] != b[i])
{
return false;
}
}
return true;
}
int main()
{
cout<<isEqual("asasa","asasa")<<endl;
return 0;
}
我的想法不是逐个比较一个字符,而是将其类型转换为 int(4 字节比较)并进行异或运算以测试它们是否相等。 我的问题是,如果只比较 require(true,false) 是否正确。
最佳答案
这是未定义的行为。 (您正在取消引用指向 int
的指针,其中指向的对象不是 int。)
代码几乎肯定会比 strcmp 慢(它通常做这样的事情 iff 指针适当对齐 - 可能循环展开几次)。
关于c++ - 我的字符串比较实现是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40673343/