题目来自网络
题目:编写字符串比较函数int Strncmp(const char* pStrF,const char* pStrS,unsigned int nCount)。
函数功能:比较字符串pStrF和pStrS的前nCount个字符。
(1)如果前nCount字节完全相等,返回值就=0;
(2)在前nCount字节比较过程中,如果出现pStrF[n]与pStrS[n]不等,则返回(pStrF[n]-pStrS[n])。
(3)如果nCount = 0,直接返回0
代码:
int Strncmp(const char* pStrF,const char* pStrS,unsigned int nCount)
{
assert(pStrF && pStrS);
while (nCount && *pStrF && *pStrS)
{
if (*pStrF != *pStrS)
{
return *pStrF - *pStrS;
}
pStrF++;
pStrS++;
nCount--;
}
if (nCount == 0)
{
return 0;
}
else
{
return *pStrF - *pStrS;
}
}
库函数代码:
int __cdecl strncmp (const char * first,const char * last,size_t count)
{
if (!count)
return(0);
while (--count && *first && *first == *last)//把第count个字符留到最后处理。
{
first++;
last++;
}
return( *(unsigned char *)first - *(unsigned char *)last );
}