1. 代码部分
#include <stdio.h>
#include <string.h>
#include <assert.h>
int mystrcmp(const char *s1, const char *s2)
{
assert( (NULL != s1) && (NULL != s2) );
while( (*s1 == *s2) && (*s1 != '\0') ) {
s1++;
s2++;
}
return *s1 - *s2;
}
int main()
{
printf("%d\n", mystrcmp("hello", "hello"));
printf("%d\n", mystrcmp("hello", "hello123"));
printf("%d\n", mystrcmp("hello", "how"));
return 0;
}
2. 运行结果
3. 拓展延伸 strncmp函数
int mystrncmp(const char *s1, const char *s2, size_t n)
{
assert(s1 != NULL && s2 != NULL);
while(n-- && *s1 == *s2)
{
s1++;
s2++;
}
return *s1 - *s2;
}