手撸strcmp
作者:
贺谦
,
2021-01-21 17:48:38
,
所有人可见
,
阅读 492
- 字符的本质是【ASCII码】
char* s1 = "China"; char* s2 = "China";
s1 == s2
比较的【两个地址】是否相等,而不是【地址指向的内容】是否相等
#include <stdio.h>
int my_strcmp(char* s1, char* s2)
{
while (*s1 != '\0' && *s2 != '\0')
{
if (*s1 > *s2) return 1;
else if (*s1 < *s2) return -1;
else
{
s1 ++;
s2 ++;
}
}
if (*s1 == '\0' && *s2 != '\0') return -1;
else if (*s1 != '\0' && *s2 == '\0') return 1;
else return 0;
}
// 优化后
int myStrcmp(char* s1, char* s2)
{
for (; *s1 && *s2; s1 ++, s2 ++)
if (*s1 != *s2)
break;
return *s1 - *s2;
}
int main()
{
char* s1 = "ahina";
char* s2 = "zhina";
int ret = myStrcmp(s1, s2);
if (ret == 0) printf("s1 == s2\n");
else if (ret > 0)printf("s1 > s2\n");
else printf("s1 < s2\n");
return 0;
}