int strcmp(const char *s1, const char *s2) 该函数的功能是比较字符串s1和s2的大小,从左向右比较(按ASCII值的大小进行比较),直到出现不同的字符或遇到‘\0’为止。
int my_strcmp(const char *s1, const char *s2)
{
if(s1== NULL || s2 == NULL)
{
return ;
}
while(*s1 != '\0' && *s2 != '\0' && *s1 == *s2)
{
s1++;
s2++;
}
return *s1 - *s2;
}
int strncmp(const char *s1, const char *s2, size_t n); 该函数与strcmp函数的功能差不多,只不过只是比较前n个字符的大小。
int my_strncmp(const char *s1, const char *s2)
{
if(s1 == NULL || s2 == NULL)
{
return ;
}
while(n-- && *s1 != '\0' && *s2 != '\0' && *s1 == *s2)
{
*s1++;
*s2++;
}
return *s1 - *s2;
}
本文详细介绍了两种字符串比较方法:my_strcmp用于完整字符串比较,而my_strncmp则针对字符串的前n个字符。这两种方法均从左到右逐字符比较直至出现不同字符或字符串结束。
366

被折叠的 条评论
为什么被折叠?



