#include
#include
#define M 10
/*238-5.编写比较字符串的函数(重现strcmp函数)*/
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int Strcompare(char *s1,char *s2)
{
while(*(s1++)==*(s2++)&&*(s1++)!='0'&&*(s2++)!='0')
{
}
return *s1-*s2 ;
}
int main(int argc, char *argv[])
{
char *s1,*s2,str1[M],str2[M];
int a;
gets(str1);
gets(str2);
s1=str1;
s2=str2;
a=Strcompare(s1,s2);
printf("%d",a);
return 0;
}
主要有两个问题:
1 gets函数以回车为结尾,你的输入分别是"a b\n"和"\n",所以字符指针s1和s2并不是字符a和b;
建议:注意结束符号
2 Strcompare函数直接操作传入的s1和s2指针,进行自加操作,最后再输出差值,经过自加的指针已经改变;
建议:另外定义两个指针进行判断操作,如下
int Strcompare(char s1, char *s2)
{
char *ss1, *ss2;
ss1 = s1;
ss2 = s2;
while ((ss1++) == (ss2++) && *(ss1++) != '0'&&(ss2++) != '0')
{
}
return *s1 - *s2;
}