strcmp函数:int strcmp(const char *s1,const char *s2)
作用:若str1=str2,则返回零;若str1<str2,则返回负数;若str1>str2,则返回正数
代码如下:
#include<stdio.h>
#include<string.h>
int myStrcmp(char *s1,char *s2)
{
int ret=0;
int a=0;
int b=0;
char *baks1=s1;
char *baks2=s2;
while(*s1 && *s2 && (*s1==*s2))//取s1和s2字符串取到s1和s2最后一个相同字符之后的不相同字符
{
s1++;
s2++;
}
s1=baks1;//将s1和s2的指针回到首地址
s2=baks2;
while(*s1)
{
a+=*s1;
s1++;
}
while(*s2)
{
b+=*s2;
s2++;
}
ret =a-b;//将s1和s2各自所有字符的ascll码相加的和拿来比较大小
if(ret<0)
{
return -1;
}
if(ret>0)
{
return 1;
}
return ret;
}
int main()
{
char *p1=“abcd”;
char *p2=“abcd”;
int ret=myStrcmp(p1,p2);
if(ret==0)
{
printf("两个字符串一样\n");
}
printf("RET=%d\n",ret);
return 0;
}
运行结果
结合代码和注释理解哈