int strcmp_m(const char *s1, const char *s2)
{
assert((s1 != NULL) && (s2 != NULL));
while (*s1 != '\0'&&*s2 != '\0')//字符串前面部分都相同
{
if (*s1 - *s2>0)
return 1;
if (*s1 - *s2<0)
return -1;
s1++;
s2++;
}
if (*s1 == '\0'&&*s2 != '\0')//谁先为'\0',谁就小
return -1;
if (*s2 == '\0'&&*s1 != '\0')
return 1;
return 0; //同时为'\0'
}
int strncmp_m(const char *s1, const char *s2, int n)
{
assert((s1 != NULL) && (s2 != NULL));
while (*s1 != '\0'&&*s2 != '\0'&&n)//字符串前面部分都相同
{
if (*s1 - *s2>0)
return 1;
if (*s1 - *s2<0)
return -1;
s1++;
s2++;
n--;
}
if (*s1 == '\0'&&*s2 != '\0'&&n)//谁先为'\0',谁就小
return -1;
if (*s2 == '\0'&&*s1 != '\0'&&n)
return 1;
return 0; //同时为'\0'
}
int main()
{
char *dest = "af";
char *source = "abcfq";
cout << strncmp(dest, source,3) << endl;
cout << strncmp_m(dest, source, 3) << endl;
system("pause");
return 0;
}