《从零开始的C语言生活》实现简易的strcmp函数功能
#include <stdio.h> int MyStrcmp(char *p1,char *p2); int MyStrcmp(char *p1,char *p2){ for(;*p1==*p2;p1++,p2++){ if(*p1=='\0'){ return 0; } } return *p1-*p2; } int main() { char a[]="Hello"; char b[]="Helly"; printf("diffrence %d\n",MyStrcmp(a,b)); char c[]="word"; char d[]="word"; printf("same result is: %d",MyStrcmp(c,d)); }
亦或是使用下面的代码
#include <stdio.h> int MyStrcmp(char s[],char t[]){ int i; for(i=0;s[i]==t[i];i++){ if(s[i]=='\0'){ return 0; } } return (s[i]-t[i]); } int main() { char a[]="Hello"; char b[]="Helly"; printf("diffrence %d\n",MyStrcmp(a,b)); char c[]="word"; char d[]="word"; printf("same result is: %d",MyStrcmp(c,d)); }