1 #include<stdio.h>
2 #include<stdlib.h>
3
4 int main(){ 5 setvbuf(stdout,NULL,_IONBF,0); 6 char s1[255],s2[255]; 7 int strcmp(char *,char *); 8 int result; 9
10 printf("1st string:"); 11 gets(s1); 12 printf("2nd string:"); 13 gets(s2); 14 result=strcmp(s1,s2); 15 printf("The comparing result is %d.",result); 16
17 return EXIT_SUCCESS; 18 } 19
20 int strcmp(char *p1,char *p2){ 21 int i; 22 int result; 23
24 result=0; //先假设两个字符串相等,比较结果为0
25 for(i=0;*(p1+i)&&*(p2+i);i++) //比较两个字符串中的对应字符都不为\0的情况
26 { 27 if(*(p1+i)!=*(p2+i)) 28 { 29 result=*(p1+i)-*(p2+i); 30 break; 31 } 32 } 33
34 //若两个字符串的长度不相等,但有字符的部分是完全相同的,退出上述循环后,result还是0
35 if(result==0) 36 result=*(p1+i)-*(p2+i); 37 return result; 38 }
下面是谭浩强的答案,比较简单。我还是不能灵活运用while语句
1 #include<stdio.h>
2 #include<stdlib.h>
3
4 int main(){ 5 setvbuf(stdout,NULL,_IONBF,0); 6 char s1[255],s2[255]; 7 int strcmp(char *,char *); 8 int result; 9
10 printf("1st string:"); 11 gets(s1); 12 printf("2nd string:"); 13 gets(s2); 14 result=strcmp(s1,s2); 15 printf("The comparing result is %d.",result); 16
17 return EXIT_SUCCESS; 18 } 19
20 int strcmp(char *p1,char *p2){ 21 int i=0; 22 int result; 23
24 while(*(p1+i)==*(p2+i)) 25 if(*(p1+i++)=='\0') 26 result=0; 27 result=*(p1+i)-*(p2+i); 28
29 return result; 30 }
