用函数实现对两个字符串str1和str2的比较:strcmp (str1,str2)

本人新手,尽量用比较简单的语句,谢谢了
用函数实现,不能直接用strcmp (str1,str2)

这个函数是 字符串内字符自左向右逐个比较(按ASCII值大小相比较),直到出现不同的字符或遇'\0'为止。
当str1<str2时,返回值<0
当str1=str2时,返回值=0
当str1>str2时,返回值>0

程序如下:
int strcmp(char * str1,char * str2)
{
int i=0,temp=0,ans=0;

while((str1[i]!='\0')&&(str2[i]!='\0'))
{
temp=str1[i]-str2[i];
if(temp==0)
{
i++;
continue;
}
else
{
ans=temp;
break;
}
}
return ans;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-07-11
c语言呀?很多年不用了,但给你个提示
1、len分别测2个字符串的长度,如果长度不等,必然不同
2、如果长度相同,for循环,逐位比较,如果不同,break
3、全部相同,即2字符串相同
第2个回答  2010-07-11
if(strcmp (str1,str2)==0)则两个字符串相等,
else if(strcmp (str1,str2)>0)则字符串str1大于字符串str2
else if(strcmp (str1,str2)<0)则字符串str1小于字符串str2
第3个回答  2010-07-11
//---------------------------------------------------------------------------

#include <stdio.h>
int strcmp(const char *a,const char *b)
{
int i ;
for (i = 0; a[i]&&b[i]; i++)
if (a[i]!=b[i]) break;

return a[i]-b[i];
}
int main(void)
{
char a[]="abc";
char b[]="abd";
printf("%d",strcmp(a,b));
return 0;
}
//---------------------------------------------------------------------------
相似回答