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 }