自己写的版本
int strncmp(char *s1, char *s2, int maxlen)
{
if(!s1||!s2) cout<<"string null";
if(maxlen>strlen(s1)||maxlen>strlen(s2)) cout<<"exceed string length";
int i=0;
while(i<maxlen&&s1[i]==s2[i])
i++;
if(i==maxlen)return 0;
if(s1[i]!=s2[i])
return s1[i]-s2[i]>0?1:-1;
}ANSI C版本(难懂= =) 360doc.com/content/11/0422/23/1317564_111662313.shtml
#include <string.h>
int strncmp(register const char *s1, register const char *s2, register size_t n)
{
if (n)
{
do
{
if (*s1 != *s2++)
break;
if (*s1++ == '\0')
return 0;
} while (--n > 0);
if (n > 0)
{
if (*s1 == '\0') return -1;
if (*--s2 == '\0') return 1;
return (unsigned char) *s1 - (unsigned char) *s2;
}
}
return 0;
}某重复多遍的博客 blog.sina.com.cn/s/blog_4af62c070100ppit.html
感觉为啥都不判断指针为空的情况,而且如果s2短,maxlen还超过s2长度了,岂不是出错了,不懂啊
int strncmp ( char * s1, char * s2, size_t n)
{
if ( !n )//n为无符号整形变量;如果n为0,则返回0
return(0);
//在接下来的while函数中
//第一个循环条件:--n,如果比较到前n个字符则退出循环
//第二个循环条件:*s1,如果s1指向的字符串末尾退出循环
//第二个循环条件:*s1 == *s2,如果两字符比较不等则退出循环
while (--n && *s1 && *s1 == *s2)
{
s1++;//S1指针自加1,指向下一个字符
s2++;//S2指针自加1,指向下一个字符
}
return( *s1 - *s2 );//返回比较结果
}而且ANSI也没考虑空指针的情况,可能调用前已经处理掉了么
2965

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



