本文主要是介绍实现strcmp()函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一)strcmp()源代码
/***
*strcmp - compare two strings, returning less than, equal to, or greater than
*
*Purpose:
* STRCMP compares two strings and returns an integer
* to indicate whether the first is less than the second, the two are
* equal, or whether the first is greater than the second.
*
* Comparison is done byte by byte on an UNSIGNED basis, which is to
* say that Null (0) is less than any other character (1-255).
*
*Entry:
* const char * src - string for left-hand side of comparison
* const char * dst - string for right-hand side of comparison
*
*Exit:
* returns -1 if src < dst
* returns 0 if src == dst
* returns +1 if src > dst
*
*Exceptions:
*
*******************************************************************************/int __cdecl strcmp (const char * src,const char * dst)
{int ret = 0 ;//直到src和dst当前数值不相等且dst不为'\0'时,退出whilewhile( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst) ++src, ++dst;if ( ret < 0 )ret = -1 ;else if ( ret > 0 )ret = 1 ;return( ret );
}
说明:我们要看的是while循环这个语句, ! (ret = *(unsigned char *)src - *(unsigned char *)dst)意思是拿指针变量src所指向的字符值(即*src)减去指针变量dst所指向的字符值(即*dst),差值赋给ret,再取非运算,最后与*dst进行与运算;
拿abc<abcd举例,第一次因为a=a,则执行++src, ++dst;2次自加后,ret值为负,跳出while语句,执行if语句的判断,输出为-1;
这里要注意的是:
1.unsigned char*是强制转换类型。
2.若src和dst都为空串,返回值是多少呢?因为空串不是指地址为空,还是有地址的,这样就很明确了。
二)实现的strcmp()函数
#include "stdio.h"int strcmp(const char *pStr1, const char *pStr2)
{if(NULL == pStr1 && NULL == pStr2){return 0;}while(('\0' != *pStr1) && ('\0' != *pStr2)){if(*pStr1 < *pStr2){return -1;}else if(*pStr1 > *pStr2){return 1;}else{++ pStr1, ++ pStr2;}}if(('\0' == *pStr1) && ('\0' == *pStr2)){return 0;}else if(('\0' == *pStr1) && ('\0' != *pStr2)){return -1;}else {return 1;}
}
int main()
{char str1[] = "abcdeftghhlllg";char str2[] = "abcdeftghhtthhh";printf("the Result is: %d\n",strcmp(str1, str2));return 0;
}
这篇关于实现strcmp()函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!