strcmp() function implementation
Hey,
How is the strcmp(char*, char*) implemented?
I need to implement it myself for my Comp Science class, and this is what I got:
PHP Code:
int strcmp(const char* s1, const char* s2)
{
const char* p1 = s1 - 1;
const char* p2 = s2 - 1;
while (*++p2 == *++p1)
if (!*p2 || !*p1)
break;
if (*p2 > *p1)
return (-1);
else if (*p1 > *p2)
return (1);
return (0);
}
But it looks too long and clumsy for such a simple function.
Thanks.
Re: strcmp() function implementation
Here, nice and simple:
int strcmp(char *str1, char *str2)
{
int i;
for (i=0;str1[i]==str2[i];i++)
if (str1[i] == '\0') return 0;
return str1[i] - str2[i];
}
Re: strcmp() function implementation
Is it better..?
int strcmp(const char* a, const char* b)
{
while(*a++ == *b++)
if(*a == '\0' && *b == '\0') return 0;
return -1;
}