strcmp的实现
两个字符串怎么比较呢?
如果两个字符串相同,则相等,如果不想等,则比较ASCII,ASCII大的一方大
#include <iostream>
#include <assert.h>
using namespace std;
/*
比较s1,s2 返回值
s1 = s2 0
s1>s2 正数
s1<s2 负数
*/
int str_cmp(const char* s1, const char * s2){
assert( (s1!=NULL) && (s2!=NULL));
while (*s1 && *s1==*s2 ) { //当s1或s2有值,并且*s1==*s2
s1++;
s2++;
}
//跳出循环则不想等
return *s1-*s2;
}
int main(int argc, const char * argv[]) {
char *string1 = "hello";
char *string2 = "hello";
char *string3 = "imc";
cout<< str_cmp(string1,string2)<<endl;
cout<< str_cmp(string1,string3)<<endl;
return 0;
}