I tried to implement strcmp
:
int strCmp(char string1[], char string2[])
{
int i = 0, flag = 0;
while (flag == 0) {
if (string1[i] > string2[i]) {
flag = 1;
} else
if (string1[i] < string2[i]) {
flag = -1;
} else {
i++;
}
}
return flag;
}
but I'm stuck with the case that the user will input the same strings, because the function works with 1
and -1
, but it's doesn't return 0
. Can anyone help? And please without pointers!
Uhm.. way too complicated. Go for this one:
int strCmp(const char* s1, const char* s2)
{
while(*s1 && (*s1 == *s2))
{
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
It returns <0, 0 or >0 as expected
You can't do it without pointers. In C, indexing an array is using pointers.
Maybe you want to avoid using the *
operator? :-)
First of all standard C function strcmp
compares elements of strings as having type unsigned char
.
Secondly the parameters should be pointers to constant strings to provide the comparison also for constant strings.
The function can be written the following way
int strCmp( const char *s1, const char *s2 )
{
const unsigned char *p1 = ( const unsigned char * )s1;
const unsigned char *p2 = ( const unsigned char * )s2;
while ( *p1 && *p1 == *p2 ) ++p1, ++p2;
return ( *p1 > *p2 ) - ( *p2 > *p1 );
}
You seem to want to avoid pointer arithmetics which is a pity since that makes the solution shorter, but your problem is just that you scan beyond the end of the strings. Adding an explicit break will work. Your program slightly modified:
int strCmp(char string1[], char string2[] )
{
int i = 0;
int flag = 0;
while (flag == 0)
{
if (string1[i] > string2[i])
{
flag = 1;
}
else if (string1[i] < string2[i])
{
flag = -1;
}
if (string1[i] == '\0')
{
break;
}
i++;
}
return flag;
}
A shorter version:
int strCmp(char string1[], char string2[] )
{
for (int i = 0; ; i++)
{
if (string1[i] != string2[i])
{
return string1[i] < string2[i] ? -1 : 1;
}
if (string1[i] == '\0')
{
return 0;
}
}
}
This is a 10 opcodes implementation of strcmp (GCC assumed)
int strcmp_refactored(const char *s1, const char *s2)
{
while (1)
{
int res = ((*s1 == 0) || (*s1 != *s2));
if (__builtin_expect((res),0))
{
break;
}
++s1;
++s2;
}
return (*s1 - *s2);
}
You can try this implementation and compare to others https://godbolt.org/g/ZbMmYM
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With