#include <stdio.h>
#include <assert.h>
int strcmp(char const *str1, char const *str2)
{
int ret = 0;
assert(str1 != NULL && str2 != NULL);
while ( ! (ret = *(unsigned char*)str1 - *(unsigned char*)str2) && *str1)
{//如果当前字符相等,且前面一个指针不为空,则指针后移;
//判断指针是否为空是为了防止两个字串相等时的负作用
str1++;
str2++;
}
return ((ret>0)-(-ret>0));
}
int main()
{
char s[100];
char p[100];
gets(s);
gets(p);
if (strcmp(s,p) > 0)
{
printf("s is bigger than p\n");
}
else if (strcmp(s,p) < 0)
{
printf("s is smaller than p\n");
}
else
{
printf("s is equal to p\n");
}
return 0;
}
//linux源码
/**
* strcmp - Compare two strings
* @cs: One string
* @ct: Another string
*/
#undef strcmp
int strcmp(const char *cs, const char *ct)
{
unsigned char c1, c2;
while (1) {
c1 = *cs++; //这里包含一个强制类型转换
c2 = *ct++;
if (c1 != c2)
return c1 < c2 ? -1 : 1;
if (!c1)
break;
}
return 0;
}
/***
*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 ;
while( ! (ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst) //直到src和dst当前数值不相等且dst不为\0时退出while
++src, ++dst;
if ( ret < 0 )
ret = -1 ;
else if ( ret > 0 )
ret = 1 ;
return( ret );
}
//汇编源码
int strcmp(const char *str1, const char *str2)
{
__asm //内联汇编开始
{
mov eax ,str1 //str1 是指针,在内嵌汇编中,会自动转成 " mov eax , dword ptr [str1] "
mov ebx ,str2
xor ecx, ecx
_loop:
push eax
push ebx
movsx eax ,[eax]
movsx ebx ,[ebx]
cmp eax ,ecx
je eqends
cmp eax , ebx
jne neq
pop ebx
pop eax
inc eax
inc ebx
jmp _loop
eqends:
cmp ecx ,ebx //也就是0与ebx比较
jne neq
jmp _eq
neq:
mov eax , 1
jl small
jmp exit
small: neg eax
jmp exit
_eq:
xor eax ,eax
exit:
add esp , 8
}
}