C实现比较两个字符串是否相同,不能调整C类库里的函数

来源:百度知道 编辑:UC知道 时间:2024/06/09 00:50:19
同上

提供思路:
字符串在内存中连续存放,结束符是\0,所以利用指针取得两个字符串的首地址,然后指针指向地址递增循环并比较,直到结束符。

#include <stdio.h>

int stringEqual(const char*,const char*);

int main(void){
char* a="hello";
char* b="hello";
char* c="helloworld";
char* d="hell";
printf("a%sb\n",stringEqual(a,b)?"=":"!=");
printf("a%sc\n",stringEqual(a,c)?"=":"!=");
printf("a%sd\n",stringEqual(a,d)?"=":"!=");
}

int stringEqual(const char* x,const char* y) {
while(*x!='\0' && *y!='\0' && *x++==*y++) ;
if(*x=='\0' && *y=='\0') return 1;
else return 0;

}